Debian Codegraph @

lib-python/3/test/test_capi/test_misc.py

raw symbols SCIP
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 from collections import OrderedDict
5 import _thread
6 import contextlib
7 import importlib.machinery
8 import importlib.util
9 import os
10 import pickle
11 import random
12 import re
13 import subprocess
14 import sys
15 import textwrap
16 import threading
17 import time
18 import unittest
19 import weakref
20 from test import support
21 from test.support import MISSING_C_DOCSTRINGS
22 from test.support import import_helper
23 from test.support import threading_helper
24 from test.support import warnings_helper
25 from test.support.script_helper import assert_python_failure, assert_python_ok
26 try:
27 import _posixsubprocess
28 except ImportError:
29 _posixsubprocess = None
30 try:
31 import _testmultiphase
32 except ImportError:
33 _testmultiphase = None
34
35 # Skip this test if the _testcapi module isn't available.
36 _testcapi = import_helper.import_module('_testcapi')
37
38 try:
39 import _testinternalcapi
40 except ImportError:
41 _testinternalcapi = object()
42
43 # Were we compiled --with-pydebug or with #define Py_DEBUG?
44 Py_DEBUG = hasattr(sys, 'gettotalrefcount')
45
46
47 NULL = None
48
49 def decode_stderr(err):
50 return err.decode('utf-8', 'replace').replace('\r', '')
51
52
53 def testfunction(self):
54 """some doc"""
55 return self
56
57
58 class InstanceMethod:
59 id = _testcapi.instancemethod(id)
60 testfunction = _testcapi.instancemethod(testfunction)
61
62 class CAPITest(unittest.TestCase):
63
64 def test_instancemethod(self):
65 inst = InstanceMethod()
66 self.assertEqual(id(inst), inst.id())
67 self.assertTrue(inst.testfunction() is inst)
68 self.assertEqual(inst.testfunction.__doc__, testfunction.__doc__)
69 self.assertEqual(InstanceMethod.testfunction.__doc__, testfunction.__doc__)
70
71 InstanceMethod.testfunction.attribute = "test"
72 self.assertEqual(testfunction.attribute, "test")
73 self.assertRaises(AttributeError, setattr, inst.testfunction, "attribute", "test")
74
75 @support.requires_subprocess()
76 @support.impl_detail("PyPy uses a different fatal error message format", pypy=False)
77 def test_no_FatalError_infinite_loop(self):
78 with support.SuppressCrashReport():
79 p = subprocess.Popen([sys.executable, "-c",
80 'import _testcapi;'
81 '_testcapi.crash_no_current_thread()'],
82 stdout=subprocess.PIPE,
83 stderr=subprocess.PIPE)
84 (out, err) = p.communicate()
85 self.assertEqual(out, b'')
86 # This used to cause an infinite loop.
87 self.assertTrue(err.rstrip().startswith(
88 b'Fatal Python error: '
89 b'PyThreadState_Get: '
90 b'the function must be called with the GIL held, '
91 b'but the GIL is released '
92 b'(the current Python thread state is NULL)'),
93 err)
94
95 def test_memoryview_from_NULL_pointer(self):
96 self.assertRaises(ValueError, _testcapi.make_memoryview_from_NULL_pointer)
97
98 def test_exception(self):
99 raised_exception = ValueError("5")
100 new_exc = TypeError("TEST")
101 try:
102 raise raised_exception
103 except ValueError as e:
104 orig_sys_exception = sys.exception()
105 orig_exception = _testcapi.set_exception(new_exc)
106 new_sys_exception = sys.exception()
107 new_exception = _testcapi.set_exception(orig_exception)
108 reset_sys_exception = sys.exception()
109
110 self.assertEqual(orig_exception, e)
111
112 self.assertEqual(orig_exception, raised_exception)
113 self.assertEqual(orig_sys_exception, orig_exception)
114 self.assertEqual(reset_sys_exception, orig_exception)
115 self.assertEqual(new_exception, new_exc)
116 self.assertEqual(new_sys_exception, new_exception)
117 else:
118 self.fail("Exception not raised")
119
120 def test_exc_info(self):
121 raised_exception = ValueError("5")
122 new_exc = TypeError("TEST")
123 try:
124 raise raised_exception
125 except ValueError as e:
126 tb = e.__traceback__
127 orig_sys_exc_info = sys.exc_info()
128 orig_exc_info = _testcapi.set_exc_info(new_exc.__class__, new_exc, None)
129 new_sys_exc_info = sys.exc_info()
130 new_exc_info = _testcapi.set_exc_info(*orig_exc_info)
131 reset_sys_exc_info = sys.exc_info()
132
133 self.assertEqual(orig_exc_info[1], e)
134
135 self.assertSequenceEqual(orig_exc_info, (raised_exception.__class__, raised_exception, tb))
136 self.assertSequenceEqual(orig_sys_exc_info, orig_exc_info)
137 self.assertSequenceEqual(reset_sys_exc_info, orig_exc_info)
138 self.assertSequenceEqual(new_exc_info, (new_exc.__class__, new_exc, None))
139 self.assertSequenceEqual(new_sys_exc_info, new_exc_info)
140 else:
141 self.assertTrue(False)
142
143 def test_set_object(self):
144 # new exception as obj is not an exception
145 with self.assertRaises(ValueError) as e:
146 _testcapi.exc_set_object(ValueError, 42)
147 self.assertEqual(e.exception.args, (42,))
148
149 # wraps the exception because unrelated types
150 with self.assertRaises(ValueError) as e:
151 _testcapi.exc_set_object(ValueError, TypeError(1,2,3))
152 wrapped = e.exception.args[0]
153 self.assertIsInstance(wrapped, TypeError)
154 self.assertEqual(wrapped.args, (1, 2, 3))
155
156 # is superclass, so does not wrap
157 with self.assertRaises(PermissionError) as e:
158 _testcapi.exc_set_object(OSError, PermissionError(24))
159 self.assertEqual(e.exception.args, (24,))
160
161 class Meta(type):
162 def __subclasscheck__(cls, sub):
163 1/0
164
165 class Broken(Exception, metaclass=Meta):
166 pass
167
168 with self.assertRaises(ZeroDivisionError) as e:
169 _testcapi.exc_set_object(Broken, Broken())
170
171 @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
172 def test_seq_bytes_to_charp_array(self):
173 # Issue #15732: crash in _PySequence_BytesToCharpArray()
174 class Z(object):
175 def __len__(self):
176 return 1
177 if sys.implementation.name == 'pypy':
178 msg = "iterable"
179 else:
180 msg = "indexing"
181 with self.assertRaisesRegex(TypeError, msg):
182 _posixsubprocess.fork_exec(
183 1,Z(),True,(1, 2),5,6,7,8,9,10,11,12,13,14,True,True,17,False,19,20,21,22,False)
184 # Issue #15736: overflow in _PySequence_BytesToCharpArray()
185 class Z(object):
186 def __len__(self):
187 return sys.maxsize
188 def __getitem__(self, i):
189 return b'x'
190 self.assertRaises(MemoryError, _posixsubprocess.fork_exec,
191 1,Z(),True,(1, 2),5,6,7,8,9,10,11,12,13,14,True,True,17,False,19,20,21,22,False)
192
193 @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
194 def test_subprocess_fork_exec(self):
195 class Z(object):
196 def __len__(self):
197 return 1
198
199 # Issue #15738: crash in subprocess_fork_exec()
200 self.assertRaises(TypeError, _posixsubprocess.fork_exec,
201 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)
202
203 @unittest.skipIf(MISSING_C_DOCSTRINGS,
204 "Signature information for builtins requires docstrings")
205 def test_docstring_signature_parsing(self):
206
207 self.assertEqual(_testcapi.no_docstring.__doc__, None)
208 self.assertEqual(_testcapi.no_docstring.__text_signature__, None)
209
210 self.assertEqual(_testcapi.docstring_empty.__doc__, None)
211 self.assertEqual(_testcapi.docstring_empty.__text_signature__, None)
212
213 self.assertEqual(_testcapi.docstring_no_signature.__doc__,
214 "This docstring has no signature.")
215 self.assertEqual(_testcapi.docstring_no_signature.__text_signature__, None)
216
217 self.assertEqual(_testcapi.docstring_with_invalid_signature.__doc__,
218 "docstring_with_invalid_signature($module, /, boo)\n"
219 "\n"
220 "This docstring has an invalid signature."
221 )
222 self.assertEqual(_testcapi.docstring_with_invalid_signature.__text_signature__, None)
223
224 self.assertEqual(_testcapi.docstring_with_invalid_signature2.__doc__,
225 "docstring_with_invalid_signature2($module, /, boo)\n"
226 "\n"
227 "--\n"
228 "\n"
229 "This docstring also has an invalid signature."
230 )
231 self.assertEqual(_testcapi.docstring_with_invalid_signature2.__text_signature__, None)
232
233 self.assertEqual(_testcapi.docstring_with_signature.__doc__,
234 "This docstring has a valid signature.")
235 self.assertEqual(_testcapi.docstring_with_signature.__text_signature__, "($module, /, sig)")
236
237 self.assertEqual(_testcapi.docstring_with_signature_but_no_doc.__doc__, None)
238 self.assertEqual(_testcapi.docstring_with_signature_but_no_doc.__text_signature__,
239 "($module, /, sig)")
240
241 self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__doc__,
242 "\nThis docstring has a valid signature and some extra newlines.")
243 self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__text_signature__,
244 "($module, /, parameter)")
245
246 def test_c_type_with_matrix_multiplication(self):
247 M = _testcapi.matmulType
248 m1 = M()
249 m2 = M()
250 self.assertEqual(m1 @ m2, ("matmul", m1, m2))
251 self.assertEqual(m1 @ 42, ("matmul", m1, 42))
252 self.assertEqual(42 @ m1, ("matmul", 42, m1))
253 o = m1
254 o @= m2
255 self.assertEqual(o, ("imatmul", m1, m2))
256 o = m1
257 o @= 42
258 self.assertEqual(o, ("imatmul", m1, 42))
259 o = 42
260 o @= m1
261 self.assertEqual(o, ("matmul", 42, m1))
262
263 def test_c_type_with_ipow(self):
264 # When the __ipow__ method of a type was implemented in C, using the
265 # modulo param would cause segfaults.
266 o = _testcapi.ipowType()
267 self.assertEqual(o.__ipow__(1), (1, None))
268 self.assertEqual(o.__ipow__(2, 2), (2, 2))
269
270 def test_return_null_without_error(self):
271 # Issue #23571: A function must not return NULL without setting an
272 # error
273 if Py_DEBUG:
274 code = textwrap.dedent("""
275 import _testcapi
276 from test import support
277
278 with support.SuppressCrashReport():
279 _testcapi.return_null_without_error()
280 """)
281 rc, out, err = assert_python_failure('-c', code)
282 err = decode_stderr(err)
283 self.assertRegex(err,
284 r'Fatal Python error: _Py_CheckFunctionResult: '
285 r'a function returned NULL without setting an exception\n'
286 r'Python runtime state: initialized\n'
287 r'SystemError: <built-in function return_null_without_error> '
288 r'returned NULL without setting an exception\n'
289 r'\n'
290 r'Current thread.*:\n'
291 r' File .*", line 6 in <module>\n')
292 elif sys.implementation.name == 'pypy':
293 with self.assertRaises(SystemError) as cm:
294 _testcapi.return_null_without_error()
295 self.assertRegex(str(cm.exception),
296 'returned NULL without setting an exception')
297 else:
298 with self.assertRaises(SystemError) as cm:
299 _testcapi.return_null_without_error()
300 self.assertRegex(str(cm.exception),
301 'return_null_without_error.* ')
302
303 def test_return_result_with_error(self):
304 # Issue #23571: A function must not return a result with an error set
305 if Py_DEBUG:
306 code = textwrap.dedent("""
307 import _testcapi
308 from test import support
309
310 with support.SuppressCrashReport():
311 _testcapi.return_result_with_error()
312 """)
313 rc, out, err = assert_python_failure('-c', code)
314 err = decode_stderr(err)
315 self.assertRegex(err,
316 r'Fatal Python error: _Py_CheckFunctionResult: '
317 r'a function returned a result with an exception set\n'
318 r'Python runtime state: initialized\n'
319 r'ValueError\n'
320 r'\n'
321 r'The above exception was the direct cause '
322 r'of the following exception:\n'
323 r'\n'
324 r'SystemError: <built-in '
325 r'function return_result_with_error> '
326 r'returned a result with an exception set\n'
327 r'\n'
328 r'Current thread.*:\n'
329 r' File .*, line 6 in <module>\n')
330 elif sys.implementation.name == 'pypy':
331 with self.assertRaises(SystemError) as cm:
332 _testcapi.return_result_with_error()
333 self.assertRegex(str(cm.exception),
334 'returned a result with an exception set')
335 else:
336 with self.assertRaises(SystemError) as cm:
337 _testcapi.return_result_with_error()
338 self.assertRegex(str(cm.exception),
339 'return_result_with_error.*')
340
341 def test_getitem_with_error(self):
342 # Test _Py_CheckSlotResult(). Raise an exception and then calls
343 # PyObject_GetItem(): check that the assertion catches the bug.
344 # PyObject_GetItem() must not be called with an exception set.
345 code = textwrap.dedent("""
346 import _testcapi
347 from test import support
348
349 with support.SuppressCrashReport():
350 _testcapi.getitem_with_error({1: 2}, 1)
351 """)
352 rc, out, err = assert_python_failure('-c', code)
353 err = decode_stderr(err)
354 if 'SystemError: ' not in err:
355 self.assertRegex(err,
356 r'Fatal Python error: _Py_CheckSlotResult: '
357 r'Slot __getitem__ of type dict succeeded '
358 r'with an exception set\n'
359 r'Python runtime state: initialized\n'
360 r'ValueError: bug\n'
361 r'\n'
362 r'Current thread .* \(most recent call first\):\n'
363 r' File .*, line 6 in <module>\n'
364 r'\n'
365 r'Extension modules: _testcapi \(total: 1\)\n')
366 else:
367 # Python built with NDEBUG macro defined:
368 # test _Py_CheckFunctionResult() instead.
369 self.assertIn('returned a result with an exception set', err)
370
371 def test_buildvalue_N(self):
372 _testcapi.test_buildvalue_N()
373
374 @support.impl_detail("no allocation hooks on PyPy", pypy=False)
375 def test_set_nomemory(self):
376 code = """if 1:
377 import _testcapi
378
379 class C(): pass
380
381 # The first loop tests both functions and that remove_mem_hooks()
382 # can be called twice in a row. The second loop checks a call to
383 # set_nomemory() after a call to remove_mem_hooks(). The third
384 # loop checks the start and stop arguments of set_nomemory().
385 for outer_cnt in range(1, 4):
386 start = 10 * outer_cnt
387 for j in range(100):
388 if j == 0:
389 if outer_cnt != 3:
390 _testcapi.set_nomemory(start)
391 else:
392 _testcapi.set_nomemory(start, start + 1)
393 try:
394 C()
395 except MemoryError as e:
396 if outer_cnt != 3:
397 _testcapi.remove_mem_hooks()
398 print('MemoryError', outer_cnt, j)
399 _testcapi.remove_mem_hooks()
400 break
401 """
402 rc, out, err = assert_python_ok('-c', code)
403 lines = out.splitlines()
404 for i, line in enumerate(lines, 1):
405 self.assertIn(b'MemoryError', out)
406 *_, count = line.split(b' ')
407 count = int(count)
408 self.assertLessEqual(count, i*5)
409 self.assertGreaterEqual(count, i*5-2)
410
411 def test_mapping_keys_values_items(self):
412 class Mapping1(dict):
413 def keys(self):
414 return list(super().keys())
415 def values(self):
416 return list(super().values())
417 def items(self):
418 return list(super().items())
419 class Mapping2(dict):
420 def keys(self):
421 return tuple(super().keys())
422 def values(self):
423 return tuple(super().values())
424 def items(self):
425 return tuple(super().items())
426 dict_obj = {'foo': 1, 'bar': 2, 'spam': 3}
427
428 for mapping in [{}, OrderedDict(), Mapping1(), Mapping2(),
429 dict_obj, OrderedDict(dict_obj),
430 Mapping1(dict_obj), Mapping2(dict_obj)]:
431 self.assertListEqual(_testcapi.get_mapping_keys(mapping),
432 list(mapping.keys()))
433 self.assertListEqual(_testcapi.get_mapping_values(mapping),
434 list(mapping.values()))
435 self.assertListEqual(_testcapi.get_mapping_items(mapping),
436 list(mapping.items()))
437
438 def test_mapping_keys_values_items_bad_arg(self):
439 self.assertRaises(AttributeError, _testcapi.get_mapping_keys, None)
440 self.assertRaises(AttributeError, _testcapi.get_mapping_values, None)
441 self.assertRaises(AttributeError, _testcapi.get_mapping_items, None)
442
443 class BadMapping:
444 def keys(self):
445 return None
446 def values(self):
447 return None
448 def items(self):
449 return None
450 bad_mapping = BadMapping()
451 self.assertRaises(TypeError, _testcapi.get_mapping_keys, bad_mapping)
452 self.assertRaises(TypeError, _testcapi.get_mapping_values, bad_mapping)
453 self.assertRaises(TypeError, _testcapi.get_mapping_items, bad_mapping)
454
455 def test_mapping_has_key(self):
456 dct = {'a': 1}
457 self.assertTrue(_testcapi.mapping_has_key(dct, 'a'))
458 self.assertFalse(_testcapi.mapping_has_key(dct, 'b'))
459
460 class SubDict(dict):
461 pass
462
463 dct2 = SubDict({'a': 1})
464 self.assertTrue(_testcapi.mapping_has_key(dct2, 'a'))
465 self.assertFalse(_testcapi.mapping_has_key(dct2, 'b'))
466
467 def test_sequence_set_slice(self):
468 # Correct case:
469 data = [1, 2, 3, 4, 5]
470 data_copy = data.copy()
471
472 _testcapi.sequence_set_slice(data, 1, 3, [8, 9])
473 data_copy[1:3] = [8, 9]
474 self.assertEqual(data, data_copy)
475 self.assertEqual(data, [1, 8, 9, 4, 5])
476
477 # Custom class:
478 class Custom:
479 def __setitem__(self, index, value):
480 self.index = index
481 self.value = value
482
483 c = Custom()
484 _testcapi.sequence_set_slice(c, 0, 5, 'abc')
485 self.assertEqual(c.index, slice(0, 5))
486 self.assertEqual(c.value, 'abc')
487
488 # Immutable sequences must raise:
489 bad_seq1 = (1, 2, 3, 4)
490 with self.assertRaises(TypeError):
491 _testcapi.sequence_set_slice(bad_seq1, 1, 3, (8, 9))
492 self.assertEqual(bad_seq1, (1, 2, 3, 4))
493
494 bad_seq2 = 'abcd'
495 with self.assertRaises(TypeError):
496 _testcapi.sequence_set_slice(bad_seq2, 1, 3, 'xy')
497 self.assertEqual(bad_seq2, 'abcd')
498
499 # Not a sequence:
500 with self.assertRaises(TypeError):
501 _testcapi.sequence_set_slice(None, 1, 3, 'xy')
502
503 mapping = {1: 'a', 2: 'b', 3: 'c'}
504 with self.assertRaises(TypeError):
505 _testcapi.sequence_set_slice(mapping, 1, 3, 'xy')
506 self.assertEqual(mapping, {1: 'a', 2: 'b', 3: 'c'})
507
508 def test_sequence_del_slice(self):
509 # Correct case:
510 data = [1, 2, 3, 4, 5]
511 data_copy = data.copy()
512
513 _testcapi.sequence_del_slice(data, 1, 3)
514 del data_copy[1:3]
515 self.assertEqual(data, data_copy)
516 self.assertEqual(data, [1, 4, 5])
517
518 # Custom class:
519 class Custom:
520 def __delitem__(self, index):
521 self.index = index
522
523 c = Custom()
524 _testcapi.sequence_del_slice(c, 0, 5)
525 self.assertEqual(c.index, slice(0, 5))
526
527 # Immutable sequences must raise:
528 bad_seq1 = (1, 2, 3, 4)
529 with self.assertRaises(TypeError):
530 _testcapi.sequence_del_slice(bad_seq1, 1, 3)
531 self.assertEqual(bad_seq1, (1, 2, 3, 4))
532
533 bad_seq2 = 'abcd'
534 with self.assertRaises(TypeError):
535 _testcapi.sequence_del_slice(bad_seq2, 1, 3)
536 self.assertEqual(bad_seq2, 'abcd')
537
538 # Not a sequence:
539 with self.assertRaises(TypeError):
540 _testcapi.sequence_del_slice(None, 1, 3)
541
542 mapping = {1: 'a', 2: 'b', 3: 'c'}
543 with self.assertRaises(TypeError):
544 _testcapi.sequence_del_slice(mapping, 1, 3)
545 self.assertEqual(mapping, {1: 'a', 2: 'b', 3: 'c'})
546
547 @unittest.skipUnless(hasattr(_testcapi, 'negative_refcount'),
548 'need _testcapi.negative_refcount')
549 def test_negative_refcount(self):
550 # bpo-35059: Check that Py_DECREF() reports the correct filename
551 # when calling _Py_NegativeRefcount() to abort Python.
552 code = textwrap.dedent("""
553 import _testcapi
554 from test import support
555
556 with support.SuppressCrashReport():
557 _testcapi.negative_refcount()
558 """)
559 rc, out, err = assert_python_failure('-c', code)
560 self.assertRegex(err,
561 br'_testcapimodule\.c:[0-9]+: '
562 br'_Py_NegativeRefcount: Assertion failed: '
563 br'object has negative ref count')
564
565 def test_trashcan_subclass(self):
566 # bpo-35983: Check that the trashcan mechanism for "list" is NOT
567 # activated when its tp_dealloc is being called by a subclass
568 from _testcapi import MyList
569 L = None
570 for i in range(1000):
571 L = MyList((L,))
572
573 @support.requires_resource('cpu')
574 @support.impl_detail("no trashcan on PyPy", pypy=False)
575 def test_trashcan_python_class1(self):
576 self.do_test_trashcan_python_class(list)
577
578 @support.requires_resource('cpu')
579 @support.impl_detail("no trashcan on PyPy", pypy=False)
580 def test_trashcan_python_class2(self):
581 from _testcapi import MyList
582 self.do_test_trashcan_python_class(MyList)
583
584 def do_test_trashcan_python_class(self, base):
585 # Check that the trashcan mechanism works properly for a Python
586 # subclass of a class using the trashcan (this specific test assumes
587 # that the base class "base" behaves like list)
588 class PyList(base):
589 # Count the number of PyList instances to verify that there is
590 # no memory leak
591 num = 0
592 def __init__(self, *args):
593 __class__.num += 1
594 super().__init__(*args)
595 def __del__(self):
596 __class__.num -= 1
597
598 for parity in (0, 1):
599 L = None
600 # We need in the order of 2**20 iterations here such that a
601 # typical 8MB stack would overflow without the trashcan.
602 for i in range(2**20):
603 L = PyList((L,))
604 L.attr = i
605 if parity:
606 # Add one additional nesting layer
607 L = (L,)
608 self.assertGreater(PyList.num, 0)
609 del L
610 self.assertEqual(PyList.num, 0)
611
612 @unittest.skipIf(MISSING_C_DOCSTRINGS,
613 "Signature information for builtins requires docstrings")
614 def test_heap_ctype_doc_and_text_signature(self):
615 self.assertEqual(_testcapi.HeapDocCType.__doc__, "somedoc")
616 self.assertEqual(_testcapi.HeapDocCType.__text_signature__, "(arg1, arg2)")
617
618 def test_null_type_doc(self):
619 self.assertEqual(_testcapi.NullTpDocType.__doc__, None)
620
621 @support.refcount_test
622 def test_subclass_of_heap_gc_ctype_with_tpdealloc_decrefs_once(self):
623 class HeapGcCTypeSubclass(_testcapi.HeapGcCType):
624 def __init__(self):
625 self.value2 = 20
626 super().__init__()
627
628 subclass_instance = HeapGcCTypeSubclass()
629 type_refcnt = sys.getrefcount(HeapGcCTypeSubclass)
630
631 # Test that subclass instance was fully created
632 self.assertEqual(subclass_instance.value, 10)
633 self.assertEqual(subclass_instance.value2, 20)
634
635 # Test that the type reference count is only decremented once
636 del subclass_instance
637 self.assertEqual(type_refcnt - 1, sys.getrefcount(HeapGcCTypeSubclass))
638
639 @support.refcount_test
640 def test_subclass_of_heap_gc_ctype_with_del_modifying_dunder_class_only_decrefs_once(self):
641 class A(_testcapi.HeapGcCType):
642 def __init__(self):
643 self.value2 = 20
644 super().__init__()
645
646 class B(A):
647 def __init__(self):
648 super().__init__()
649
650 def __del__(self):
651 self.__class__ = A
652 A.refcnt_in_del = sys.getrefcount(A)
653 B.refcnt_in_del = sys.getrefcount(B)
654
655 subclass_instance = B()
656 type_refcnt = sys.getrefcount(B)
657 new_type_refcnt = sys.getrefcount(A)
658
659 # Test that subclass instance was fully created
660 self.assertEqual(subclass_instance.value, 10)
661 self.assertEqual(subclass_instance.value2, 20)
662
663 del subclass_instance
664
665 # Test that setting __class__ modified the reference counts of the types
666 if Py_DEBUG:
667 # gh-89373: In debug mode, _Py_Dealloc() keeps a strong reference
668 # to the type while calling tp_dealloc()
669 self.assertEqual(type_refcnt, B.refcnt_in_del)
670 else:
671 self.assertEqual(type_refcnt - 1, B.refcnt_in_del)
672 self.assertEqual(new_type_refcnt + 1, A.refcnt_in_del)
673
674 # Test that the original type already has decreased its refcnt
675 self.assertEqual(type_refcnt - 1, sys.getrefcount(B))
676
677 # Test that subtype_dealloc decref the newly assigned __class__ only once
678 self.assertEqual(new_type_refcnt, sys.getrefcount(A))
679
680 def test_heaptype_with_dict(self):
681 inst = _testcapi.HeapCTypeWithDict()
682 inst.foo = 42
683 self.assertEqual(inst.foo, 42)
684 self.assertEqual(inst.dictobj, inst.__dict__)
685 self.assertEqual(inst.dictobj, {"foo": 42})
686
687 inst = _testcapi.HeapCTypeWithDict()
688 self.assertEqual({}, inst.__dict__)
689
690 def test_heaptype_with_negative_dict(self):
691 inst = _testcapi.HeapCTypeWithNegativeDict()
692 inst.foo = 42
693 self.assertEqual(inst.foo, 42)
694 self.assertEqual(inst.dictobj, inst.__dict__)
695 self.assertEqual(inst.dictobj, {"foo": 42})
696
697 inst = _testcapi.HeapCTypeWithNegativeDict()
698 self.assertEqual({}, inst.__dict__)
699
700 @support.impl_detail("PyPy does not maintain the C-struct weakref list at tp_weaklistoffset", pypy=False)
701 def test_heaptype_with_weakref(self):
702 inst = _testcapi.HeapCTypeWithWeakref()
703 ref = weakref.ref(inst)
704 self.assertEqual(ref(), inst)
705 self.assertEqual(inst.weakreflist, ref)
706
707 def test_heaptype_with_buffer(self):
708 inst = _testcapi.HeapCTypeWithBuffer()
709 b = bytes(inst)
710 self.assertEqual(b, b"1234")
711
712 @support.impl_detail("no getrefcount in PyPy", pypy=False)
713 def test_c_subclass_of_heap_ctype_with_tpdealloc_decrefs_once(self):
714 subclass_instance = _testcapi.HeapCTypeSubclass()
715 type_refcnt = sys.getrefcount(_testcapi.HeapCTypeSubclass)
716
717 # Test that subclass instance was fully created
718 self.assertEqual(subclass_instance.value, 10)
719 self.assertEqual(subclass_instance.value2, 20)
720
721 # Test that the type reference count is only decremented once
722 del subclass_instance
723 self.assertEqual(type_refcnt - 1, sys.getrefcount(_testcapi.HeapCTypeSubclass))
724
725 @support.impl_detail("no getrefcount in PyPy", pypy=False)
726 def test_c_subclass_of_heap_ctype_with_del_modifying_dunder_class_only_decrefs_once(self):
727 subclass_instance = _testcapi.HeapCTypeSubclassWithFinalizer()
728 type_refcnt = sys.getrefcount(_testcapi.HeapCTypeSubclassWithFinalizer)
729 new_type_refcnt = sys.getrefcount(_testcapi.HeapCTypeSubclass)
730
731 # Test that subclass instance was fully created
732 self.assertEqual(subclass_instance.value, 10)
733 self.assertEqual(subclass_instance.value2, 20)
734
735 # The tp_finalize slot will set __class__ to HeapCTypeSubclass
736 del subclass_instance
737
738 # Test that setting __class__ modified the reference counts of the types
739 if Py_DEBUG:
740 # gh-89373: In debug mode, _Py_Dealloc() keeps a strong reference
741 # to the type while calling tp_dealloc()
742 self.assertEqual(type_refcnt, _testcapi.HeapCTypeSubclassWithFinalizer.refcnt_in_del)
743 else:
744 self.assertEqual(type_refcnt - 1, _testcapi.HeapCTypeSubclassWithFinalizer.refcnt_in_del)
745 self.assertEqual(new_type_refcnt + 1, _testcapi.HeapCTypeSubclass.refcnt_in_del)
746
747 # Test that the original type already has decreased its refcnt
748 self.assertEqual(type_refcnt - 1, sys.getrefcount(_testcapi.HeapCTypeSubclassWithFinalizer))
749
750 # Test that subtype_dealloc decref the newly assigned __class__ only once
751 self.assertEqual(new_type_refcnt, sys.getrefcount(_testcapi.HeapCTypeSubclass))
752
753 def test_heaptype_with_setattro(self):
754 obj = _testcapi.HeapCTypeSetattr()
755 self.assertEqual(obj.pvalue, 10)
756 obj.value = 12
757 self.assertEqual(obj.pvalue, 12)
758 del obj.value
759 self.assertEqual(obj.pvalue, 0)
760
761 def test_multiple_inheritance_ctypes_with_weakref_or_dict(self):
762
763 class Both1(_testcapi.HeapCTypeWithWeakref, _testcapi.HeapCTypeWithDict):
764 pass
765 class Both2(_testcapi.HeapCTypeWithDict, _testcapi.HeapCTypeWithWeakref):
766 pass
767
768 for cls in (_testcapi.HeapCTypeWithDict, _testcapi.HeapCTypeWithDict2,
769 _testcapi.HeapCTypeWithWeakref, _testcapi.HeapCTypeWithWeakref2):
770 for cls2 in (_testcapi.HeapCTypeWithDict, _testcapi.HeapCTypeWithDict2,
771 _testcapi.HeapCTypeWithWeakref, _testcapi.HeapCTypeWithWeakref2):
772 if cls is not cls2:
773 class S(cls, cls2):
774 pass
775 class B1(Both1, cls):
776 pass
777 class B2(Both1, cls):
778 pass
779
780 def test_pynumber_tobase(self):
781 from _testcapi import pynumber_tobase
782 self.assertEqual(pynumber_tobase(123, 2), '0b1111011')
783 self.assertEqual(pynumber_tobase(123, 8), '0o173')
784 self.assertEqual(pynumber_tobase(123, 10), '123')
785 self.assertEqual(pynumber_tobase(123, 16), '0x7b')
786 self.assertEqual(pynumber_tobase(-123, 2), '-0b1111011')
787 self.assertEqual(pynumber_tobase(-123, 8), '-0o173')
788 self.assertEqual(pynumber_tobase(-123, 10), '-123')
789 self.assertEqual(pynumber_tobase(-123, 16), '-0x7b')
790 self.assertRaises(TypeError, pynumber_tobase, 123.0, 10)
791 self.assertRaises(TypeError, pynumber_tobase, '123', 10)
792 self.assertRaises(SystemError, pynumber_tobase, 123, 0)
793
794 def check_fatal_error(self, code, expected, not_expected=()):
795 with support.SuppressCrashReport():
796 rc, out, err = assert_python_failure('-sSI', '-c', code)
797
798 err = decode_stderr(err)
799 self.assertIn('Fatal Python error: test_fatal_error: MESSAGE\n',
800 err)
801
802 match = re.search(r'^Extension modules:(.*) \(total: ([0-9]+)\)$',
803 err, re.MULTILINE)
804 if not match:
805 self.fail(f"Cannot find 'Extension modules:' in {err!r}")
806 modules = set(match.group(1).strip().split(', '))
807 total = int(match.group(2))
808
809 for name in expected:
810 self.assertIn(name, modules)
811 for name in not_expected:
812 self.assertNotIn(name, modules)
813 self.assertEqual(len(modules), total)
814
815 @support.impl_detail("PyPy does not print extension modules in Py_FatalError output", pypy=False)
816 @support.requires_subprocess()
817 def test_fatal_error(self):
818 # By default, stdlib extension modules are ignored,
819 # but not test modules.
820 expected = ('_testcapi',)
821 not_expected = ('sys',)
822 code = 'import _testcapi, sys; _testcapi.fatal_error(b"MESSAGE")'
823 self.check_fatal_error(code, expected, not_expected)
824
825 # Mark _testcapi as stdlib module, but not sys
826 expected = ('sys',)
827 not_expected = ('_testcapi',)
828 code = textwrap.dedent('''
829 import _testcapi, sys
830 sys.stdlib_module_names = frozenset({"_testcapi"})
831 _testcapi.fatal_error(b"MESSAGE")
832 ''')
833 self.check_fatal_error(code, expected)
834
835 def test_pyobject_repr_from_null(self):
836 s = _testcapi.pyobject_repr_from_null()
837 self.assertEqual(s, '<NULL>')
838
839 def test_pyobject_str_from_null(self):
840 s = _testcapi.pyobject_str_from_null()
841 self.assertEqual(s, '<NULL>')
842
843 def test_pyobject_bytes_from_null(self):
844 s = _testcapi.pyobject_bytes_from_null()
845 self.assertEqual(s, b'<NULL>')
846
847 def test_Py_CompileString(self):
848 # Check that Py_CompileString respects the coding cookie
849 _compile = _testcapi.Py_CompileString
850 code = b"# -*- coding: latin1 -*-\nprint('\xc2\xa4')\n"
851 result = _compile(code)
852 expected = compile(code, "<string>", "exec")
853 self.assertEqual(result.co_consts, expected.co_consts)
854
855 @support.impl_detail("no ctypes.pythonapi in PyPy", pypy=False)
856 def test_export_symbols(self):
857 # bpo-44133: Ensure that the "Py_FrozenMain" and
858 # "PyThread_get_thread_native_id" symbols are exported by the Python
859 # (directly by the binary, or via by the Python dynamic library).
860 ctypes = import_helper.import_module('ctypes')
861 names = []
862
863 # Test if the PY_HAVE_THREAD_NATIVE_ID macro is defined
864 if hasattr(_thread, 'get_native_id'):
865 names.append('PyThread_get_thread_native_id')
866
867 # Python/frozenmain.c fails to build on Windows when the symbols are
868 # missing:
869 # - PyWinFreeze_ExeInit
870 # - PyWinFreeze_ExeTerm
871 # - PyInitFrozenExtensions
872 if os.name != 'nt':
873 names.append('Py_FrozenMain')
874
875 for name in names:
876 with self.subTest(name=name):
877 self.assertTrue(hasattr(ctypes.pythonapi, name))
878
879 def test_eval_get_func_name(self):
880 def function_example(): ...
881
882 class A:
883 def method_example(self): ...
884
885 self.assertEqual(_testcapi.eval_get_func_name(function_example),
886 "function_example")
887 self.assertEqual(_testcapi.eval_get_func_name(A.method_example),
888 "method_example")
889 self.assertEqual(_testcapi.eval_get_func_name(A().method_example),
890 "method_example")
891 self.assertEqual(_testcapi.eval_get_func_name(sum), "sum") # c function
892 self.assertEqual(_testcapi.eval_get_func_name(A), "type")
893
894 def test_eval_get_func_desc(self):
895 def function_example(): ...
896
897 class A:
898 def method_example(self): ...
899
900 self.assertEqual(_testcapi.eval_get_func_desc(function_example),
901 "()")
902 self.assertEqual(_testcapi.eval_get_func_desc(A.method_example),
903 "()")
904 self.assertEqual(_testcapi.eval_get_func_desc(A().method_example),
905 "()")
906 self.assertEqual(_testcapi.eval_get_func_desc(sum), "()") # c function
907 self.assertEqual(_testcapi.eval_get_func_desc(A), " object")
908
909 def test_function_get_code(self):
910 import types
911
912 def some():
913 pass
914
915 code = _testcapi.function_get_code(some)
916 self.assertIsInstance(code, types.CodeType)
917 self.assertEqual(code, some.__code__)
918
919 # PyPy raises TypeError
920 with self.assertRaises((TypeError, SystemError)):
921 _testcapi.function_get_code(None) # not a function
922
923 def test_function_get_globals(self):
924 def some():
925 pass
926
927 globals_ = _testcapi.function_get_globals(some)
928 self.assertIsInstance(globals_, dict)
929 self.assertEqual(globals_, some.__globals__)
930
931 # PyPy raises AttributeError
932 with self.assertRaises((AttributeError, SystemError)):
933 _testcapi.function_get_globals(None) # not a function
934
935 def test_function_get_module(self):
936 def some():
937 pass
938
939 module = _testcapi.function_get_module(some)
940 self.assertIsInstance(module, str)
941 self.assertEqual(module, some.__module__)
942
943 # PyPy raises AttributeError
944 with self.assertRaises((AttributeError, SystemError)):
945 _testcapi.function_get_module(None) # not a function
946
947 def test_sys_setobject(self):
948 # will be in next 3.11 release
949 setobject = _testcapi.sys_setobject
950
951 value = ['value']
952 value2 = ['value2']
953 try:
954 self.assertEqual(setobject(b'newattr', value), 0)
955 self.assertIs(sys.newattr, value)
956 self.assertEqual(setobject(b'newattr', value2), 0)
957 self.assertIs(sys.newattr, value2)
958 self.assertEqual(setobject(b'newattr', NULL), 0)
959 self.assertFalse(hasattr(sys, 'newattr'))
960 self.assertEqual(setobject(b'newattr', NULL), 0)
961 finally:
962 with contextlib.suppress(AttributeError):
963 del sys.newattr
964 try:
965 self.assertEqual(setobject('\U0001f40d'.encode(), value), 0)
966 self.assertIs(getattr(sys, '\U0001f40d'), value)
967 self.assertEqual(setobject('\U0001f40d'.encode(), NULL), 0)
968 self.assertFalse(hasattr(sys, '\U0001f40d'))
969 finally:
970 with contextlib.suppress(AttributeError):
971 delattr(sys, '\U0001f40d')
972
973 with self.assertRaises(UnicodeDecodeError):
974 setobject(b'\xff', value)
975 # CRASHES setobject(NULL, value)
976
977
978 def dummy():
979 pass
980
981 can_test_pending_calls = True
982 if not(_testcapi._pending_threadfunc(dummy)):
983 # XXX PyPy does not properly implement this
984 can_test_pending_calls = False
985
986
987 @unittest.skipIf(not can_test_pending_calls, "cannot call Py_AddPendingCall")
988 class TestPendingCalls(unittest.TestCase):
989
990 def pendingcalls_submit(self, l, n):
991 def callback():
992 #this function can be interrupted by thread switching so let's
993 #use an atomic operation
994 l.append(None)
995
996 for i in range(n):
997 time.sleep(random.random()*0.02) #0.01 secs on average
998 #try submitting callback until successful.
999 #rely on regular interrupt to flush queue if we are
1000 #unsuccessful.
1001 while True:
1002 if _testcapi._pending_threadfunc(callback):
1003 break
1004
1005 def pendingcalls_wait(self, l, n, context = None):
1006 #now, stick around until l[0] has grown to 10
1007 count = 0
1008 while len(l) != n:
1009 #this busy loop is where we expect to be interrupted to
1010 #run our callbacks. Note that callbacks are only run on the
1011 #main thread
1012 if False and support.verbose:
1013 print("(%i)"%(len(l),),)
1014 for i in range(1000):
1015 a = i*i
1016 if context and not context.event.is_set():
1017 continue
1018 count += 1
1019 self.assertTrue(count < 10000,
1020 "timeout waiting for %i callbacks, got %i"%(n, len(l)))
1021 if False and support.verbose:
1022 print("(%i)"%(len(l),))
1023
1024 @threading_helper.requires_working_threading()
1025 def test_pendingcalls_threaded(self):
1026
1027 #do every callback on a separate thread
1028 n = 32 #total callbacks
1029 threads = []
1030 class foo(object):pass
1031 context = foo()
1032 context.l = []
1033 context.n = 2 #submits per thread
1034 context.nThreads = n // context.n
1035 context.nFinished = 0
1036 context.lock = threading.Lock()
1037 context.event = threading.Event()
1038
1039 threads = [threading.Thread(target=self.pendingcalls_thread,
1040 args=(context,))
1041 for i in range(context.nThreads)]
1042 with threading_helper.start_threads(threads):
1043 self.pendingcalls_wait(context.l, n, context)
1044
1045 def pendingcalls_thread(self, context):
1046 try:
1047 self.pendingcalls_submit(context.l, context.n)
1048 finally:
1049 with context.lock:
1050 context.nFinished += 1
1051 nFinished = context.nFinished
1052 if False and support.verbose:
1053 print("finished threads: ", nFinished)
1054 if nFinished == context.nThreads:
1055 context.event.set()
1056
1057 def test_pendingcalls_non_threaded(self):
1058 #again, just using the main thread, likely they will all be dispatched at
1059 #once. It is ok to ask for too many, because we loop until we find a slot.
1060 #the loop can be interrupted to dispatch.
1061 #there are only 32 dispatch slots, so we go for twice that!
1062 l = []
1063 n = 64
1064 self.pendingcalls_submit(l, n)
1065 self.pendingcalls_wait(l, n)
1066
1067 @support.impl_detail("no subinterpreters on PyPy", pypy=False)
1068 class SubinterpreterTest(unittest.TestCase):
1069
1070 @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()")
1071 def test_subinterps(self):
1072 import builtins
1073 r, w = os.pipe()
1074 code = """if 1:
1075 import sys, builtins, pickle
1076 with open({:d}, "wb") as f:
1077 pickle.dump(id(sys.modules), f)
1078 pickle.dump(id(builtins), f)
1079 """.format(w)
1080 with open(r, "rb") as f:
1081 ret = support.run_in_subinterp(code)
1082 self.assertEqual(ret, 0)
1083 self.assertNotEqual(pickle.load(f), id(sys.modules))
1084 self.assertNotEqual(pickle.load(f), id(builtins))
1085
1086 @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()")
1087 def test_subinterps_recent_language_features(self):
1088 r, w = os.pipe()
1089 code = """if 1:
1090 import pickle
1091 with open({:d}, "wb") as f:
1092
1093 @(lambda x:x) # Py 3.9
1094 def noop(x): return x
1095
1096 a = (b := f'1{{2}}3') + noop('x') # Py 3.8 (:=) / 3.6 (f'')
1097
1098 async def foo(arg): return await arg # Py 3.5
1099
1100 pickle.dump(dict(a=a, b=b), f)
1101 """.format(w)
1102
1103 with open(r, "rb") as f:
1104 ret = support.run_in_subinterp(code)
1105 self.assertEqual(ret, 0)
1106 self.assertEqual(pickle.load(f), {'a': '123x', 'b': '123'})
1107
1108 def test_mutate_exception(self):
1109 """
1110 Exceptions saved in global module state get shared between
1111 individual module instances. This test checks whether or not
1112 a change in one interpreter's module gets reflected into the
1113 other ones.
1114 """
1115 import binascii
1116
1117 support.run_in_subinterp("import binascii; binascii.Error.foobar = 'foobar'")
1118
1119 self.assertFalse(hasattr(binascii.Error, "foobar"))
1120
1121 @unittest.skipIf(_testmultiphase is None, "test requires _testmultiphase module")
1122 def test_module_state_shared_in_global(self):
1123 """
1124 bpo-44050: Extension module state should be shared between interpreters
1125 when it doesn't support sub-interpreters.
1126 """
1127 r, w = os.pipe()
1128 self.addCleanup(os.close, r)
1129 self.addCleanup(os.close, w)
1130
1131 script = textwrap.dedent(f"""
1132 import importlib.machinery
1133 import importlib.util
1134 import os
1135
1136 fullname = '_test_module_state_shared'
1137 origin = importlib.util.find_spec('_testmultiphase').origin
1138 loader = importlib.machinery.ExtensionFileLoader(fullname, origin)
1139 spec = importlib.util.spec_from_loader(fullname, loader)
1140 module = importlib.util.module_from_spec(spec)
1141 attr_id = str(id(module.Error)).encode()
1142
1143 os.write({w}, attr_id)
1144 """)
1145 exec(script)
1146 main_attr_id = os.read(r, 100)
1147
1148 ret = support.run_in_subinterp(script)
1149 self.assertEqual(ret, 0)
1150 subinterp_attr_id = os.read(r, 100)
1151 self.assertEqual(main_attr_id, subinterp_attr_id)
1152
1153
1154 class TestThreadState(unittest.TestCase):
1155
1156 @threading_helper.reap_threads
1157 @threading_helper.requires_working_threading()
1158 def test_thread_state(self):
1159 # some extra thread-state tests driven via _testcapi
1160 def target():
1161 idents = []
1162
1163 def callback():
1164 idents.append(threading.get_ident())
1165
1166 _testcapi._test_thread_state(callback)
1167 a = b = callback
1168 time.sleep(1)
1169 # Check our main thread is in the list exactly 3 times.
1170 self.assertEqual(idents.count(threading.get_ident()), 3,
1171 "Couldn't find main thread correctly in the list")
1172
1173 target()
1174 t = threading.Thread(target=target)
1175 t.start()
1176 t.join()
1177
1178 @threading_helper.reap_threads
1179 @threading_helper.requires_working_threading()
1180 def test_gilstate_ensure_no_deadlock(self):
1181 # See https://github.com/python/cpython/issues/96071
1182 code = textwrap.dedent(f"""
1183 import _testcapi
1184
1185 def callback():
1186 print('callback called')
1187
1188 _testcapi._test_thread_state(callback)
1189 """)
1190 ret = assert_python_ok('-X', 'tracemalloc', '-c', code)
1191 self.assertIn(b'callback called', ret.out)
1192
1193
1194 class Test_testcapi(unittest.TestCase):
1195 locals().update((name, getattr(_testcapi, name))
1196 for name in dir(_testcapi)
1197 if name.startswith('test_') and not name.endswith('_code'))
1198
1199 # Suppress warning from PyUnicode_FromUnicode().
1200 @warnings_helper.ignore_warnings(category=DeprecationWarning)
1201 def test_widechar(self):
1202 _testcapi.test_widechar()
1203
1204 def test_version_api_data(self):
1205 self.assertEqual(_testcapi.Py_Version, sys.hexversion)
1206
1207
1208 class Test_testinternalcapi(unittest.TestCase):
1209 locals().update((name, getattr(_testinternalcapi, name))
1210 for name in dir(_testinternalcapi)
1211 if name.startswith('test_'))
1212
1213
1214 @support.requires_subprocess()
1215 @support.impl_detail("no malloc policies on PyPy", pypy=False)
1216 class PyMemDebugTests(unittest.TestCase):
1217 PYTHONMALLOC = 'debug'
1218 # '0x04c06e0' or '04C06E0'
1219 PTR_REGEX = r'(?:0x)?[0-9a-fA-F]+'
1220
1221 def check(self, code):
1222 with support.SuppressCrashReport():
1223 out = assert_python_failure(
1224 '-c', code,
1225 PYTHONMALLOC=self.PYTHONMALLOC,
1226 # FreeBSD: instruct jemalloc to not fill freed() memory
1227 # with junk byte 0x5a, see JEMALLOC(3)
1228 MALLOC_CONF="junk:false",
1229 )
1230 stderr = out.err
1231 return stderr.decode('ascii', 'replace')
1232
1233 def test_buffer_overflow(self):
1234 out = self.check('import _testcapi; _testcapi.pymem_buffer_overflow()')
1235 regex = (r"Debug memory block at address p={ptr}: API 'm'\n"
1236 r" 16 bytes originally requested\n"
1237 r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n"
1238 r" The [0-9] pad bytes at tail={ptr} are not all FORBIDDENBYTE \(0x[0-9a-f]{{2}}\):\n"
1239 r" at tail\+0: 0x78 \*\*\* OUCH\n"
1240 r" at tail\+1: 0xfd\n"
1241 r" at tail\+2: 0xfd\n"
1242 r" .*\n"
1243 r"( The block was made by call #[0-9]+ to debug malloc/realloc.\n)?"
1244 r" Data at p: cd cd cd .*\n"
1245 r"\n"
1246 r"Enable tracemalloc to get the memory block allocation traceback\n"
1247 r"\n"
1248 r"Fatal Python error: _PyMem_DebugRawFree: bad trailing pad byte")
1249 regex = regex.format(ptr=self.PTR_REGEX)
1250 regex = re.compile(regex, flags=re.DOTALL)
1251 self.assertRegex(out, regex)
1252
1253 def test_api_misuse(self):
1254 out = self.check('import _testcapi; _testcapi.pymem_api_misuse()')
1255 regex = (r"Debug memory block at address p={ptr}: API 'm'\n"
1256 r" 16 bytes originally requested\n"
1257 r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n"
1258 r" The [0-9] pad bytes at tail={ptr} are FORBIDDENBYTE, as expected.\n"
1259 r"( The block was made by call #[0-9]+ to debug malloc/realloc.\n)?"
1260 r" Data at p: cd cd cd .*\n"
1261 r"\n"
1262 r"Enable tracemalloc to get the memory block allocation traceback\n"
1263 r"\n"
1264 r"Fatal Python error: _PyMem_DebugRawFree: bad ID: Allocated using API 'm', verified using API 'r'\n")
1265 regex = regex.format(ptr=self.PTR_REGEX)
1266 self.assertRegex(out, regex)
1267
1268 @support.impl_detail("no debug hooks on PyPy", pypy=False)
1269 def check_malloc_without_gil(self, code):
1270 out = self.check(code)
1271 expected = ('Fatal Python error: _PyMem_DebugMalloc: '
1272 'Python memory allocator called without holding the GIL')
1273 self.assertIn(expected, out)
1274
1275 @support.impl_detail("no debug hooks on PyPy", pypy=False)
1276 def test_pymem_malloc_without_gil(self):
1277 # Debug hooks must raise an error if PyMem_Malloc() is called
1278 # without holding the GIL
1279 code = 'import _testcapi; _testcapi.pymem_malloc_without_gil()'
1280 self.check_malloc_without_gil(code)
1281
1282 @support.impl_detail("no debug hooks on PyPy", pypy=False)
1283 def test_pyobject_malloc_without_gil(self):
1284 # Debug hooks must raise an error if PyObject_Malloc() is called
1285 # without holding the GIL
1286 code = 'import _testcapi; _testcapi.pyobject_malloc_without_gil()'
1287 self.check_malloc_without_gil(code)
1288
1289 def check_pyobject_is_freed(self, func_name):
1290 code = textwrap.dedent(f'''
1291 import gc, os, sys, _testcapi
1292 # Disable the GC to avoid crash on GC collection
1293 gc.disable()
1294 try:
1295 _testcapi.{func_name}()
1296 # Exit immediately to avoid a crash while deallocating
1297 # the invalid object
1298 os._exit(0)
1299 except _testcapi.error:
1300 os._exit(1)
1301 ''')
1302 assert_python_ok(
1303 '-c', code,
1304 PYTHONMALLOC=self.PYTHONMALLOC,
1305 MALLOC_CONF="junk:false",
1306 )
1307
1308 def test_pyobject_null_is_freed(self):
1309 self.check_pyobject_is_freed('check_pyobject_null_is_freed')
1310
1311 def test_pyobject_uninitialized_is_freed(self):
1312 self.check_pyobject_is_freed('check_pyobject_uninitialized_is_freed')
1313
1314 def test_pyobject_forbidden_bytes_is_freed(self):
1315 self.check_pyobject_is_freed('check_pyobject_forbidden_bytes_is_freed')
1316
1317 def test_pyobject_freed_is_freed(self):
1318 self.check_pyobject_is_freed('check_pyobject_freed_is_freed')
1319
1320
1321 @support.impl_detail("no malloc policies on PyPy", pypy=False)
1322 class PyMemMallocDebugTests(PyMemDebugTests):
1323 PYTHONMALLOC = 'malloc_debug'
1324
1325
1326 @unittest.skipUnless(support.with_pymalloc(), 'need pymalloc')
1327 @support.impl_detail("no malloc policies on PyPy", pypy=False)
1328 class PyMemPymallocDebugTests(PyMemDebugTests):
1329 PYTHONMALLOC = 'pymalloc_debug'
1330
1331
1332 @unittest.skipUnless(Py_DEBUG, 'need Py_DEBUG')
1333 @support.impl_detail("no malloc policies on PyPy", pypy=False)
1334 class PyMemDefaultTests(PyMemDebugTests):
1335 # test default allocator of Python compiled in debug mode
1336 PYTHONMALLOC = ''
1337
1338
1339 @unittest.skipIf(_testmultiphase is None, "test requires _testmultiphase module")
1340 class Test_ModuleStateAccess(unittest.TestCase):
1341 """Test access to module start (PEP 573)"""
1342
1343 # The C part of the tests lives in _testmultiphase, in a module called
1344 # _testmultiphase_meth_state_access.
1345 # This module has multi-phase initialization, unlike _testcapi.
1346
1347 def setUp(self):
1348 fullname = '_testmultiphase_meth_state_access' # XXX
1349 origin = importlib.util.find_spec('_testmultiphase').origin
1350 loader = importlib.machinery.ExtensionFileLoader(fullname, origin)
1351 spec = importlib.util.spec_from_loader(fullname, loader)
1352 module = importlib.util.module_from_spec(spec)
1353 loader.exec_module(module)
1354 self.module = module
1355
1356 def test_subclass_get_module(self):
1357 """PyType_GetModule for defining_class"""
1358 class StateAccessType_Subclass(self.module.StateAccessType):
1359 pass
1360
1361 instance = StateAccessType_Subclass()
1362 self.assertIs(instance.get_defining_module(), self.module)
1363
1364 def test_subclass_get_module_with_super(self):
1365 class StateAccessType_Subclass(self.module.StateAccessType):
1366 def get_defining_module(self):
1367 return super().get_defining_module()
1368
1369 instance = StateAccessType_Subclass()
1370 self.assertIs(instance.get_defining_module(), self.module)
1371
1372 def test_state_access(self):
1373 """Checks methods defined with and without argument clinic
1374
1375 This tests a no-arg method (get_count) and a method with
1376 both a positional and keyword argument.
1377 """
1378
1379 a = self.module.StateAccessType()
1380 b = self.module.StateAccessType()
1381
1382 methods = {
1383 'clinic': a.increment_count_clinic,
1384 'noclinic': a.increment_count_noclinic,
1385 }
1386
1387 for name, increment_count in methods.items():
1388 with self.subTest(name):
1389 self.assertEqual(a.get_count(), b.get_count())
1390 self.assertEqual(a.get_count(), 0)
1391
1392 increment_count()
1393 self.assertEqual(a.get_count(), b.get_count())
1394 self.assertEqual(a.get_count(), 1)
1395
1396 increment_count(3)
1397 self.assertEqual(a.get_count(), b.get_count())
1398 self.assertEqual(a.get_count(), 4)
1399
1400 increment_count(-2, twice=True)
1401 self.assertEqual(a.get_count(), b.get_count())
1402 self.assertEqual(a.get_count(), 0)
1403
1404 with self.assertRaises(TypeError):
1405 increment_count(thrice=3)
1406
1407 with self.assertRaises(TypeError):
1408 increment_count(1, 2, 3)
1409
1410 def test_get_module_bad_def(self):
1411 # PyType_GetModuleByDef fails gracefully if it doesn't
1412 # find what it's looking for.
1413 # see bpo-46433
1414 instance = self.module.StateAccessType()
1415 with self.assertRaises(TypeError):
1416 instance.getmodulebydef_bad_def()
1417
1418 def test_get_module_static_in_mro(self):
1419 # Here, the class PyType_GetModuleByDef is looking for
1420 # appears in the MRO after a static type (Exception).
1421 # see bpo-46433
1422 class Subclass(BaseException, self.module.StateAccessType):
1423 pass
1424 self.assertIs(Subclass().get_defining_module(), self.module)
1425
1426
1427 class Test_FrameAPI(unittest.TestCase):
1428
1429 def getframe(self):
1430 return sys._getframe()
1431
1432 def getgenframe(self):
1433 yield sys._getframe()
1434
1435 def test_frame_getters(self):
1436 frame = self.getframe()
1437 self.assertEqual(frame.f_locals, _testcapi.frame_getlocals(frame))
1438 self.assertIs(frame.f_globals, _testcapi.frame_getglobals(frame))
1439 self.assertIs(frame.f_builtins, _testcapi.frame_getbuiltins(frame))
1440 self.assertEqual(frame.f_lasti, _testcapi.frame_getlasti(frame))
1441
1442 def test_frame_get_generator(self):
1443 gen = self.getgenframe()
1444 frame = next(gen)
1445 self.assertIs(gen, _testcapi.frame_getgenerator(frame))
1446
1447 def test_frame_fback_api(self):
1448 """Test that accessing `f_back` does not cause a segmentation fault on
1449 a frame created with `PyFrame_New` (GH-99110)."""
1450 def dummy():
1451 pass
1452
1453 frame = _testcapi.frame_new(dummy.__code__, globals(), locals())
1454 # The following line should not cause a segmentation fault.
1455 self.assertIsNone(frame.f_back)
1456
1457
1458 SUFFICIENT_TO_DEOPT_AND_SPECIALIZE = 100
1459
1460 @support.impl_detail("no _testinternalcapi PyPy", pypy=False)
1461 class Test_Pep523API(unittest.TestCase):
1462
1463 def do_test(self, func, names):
1464 actual_calls = []
1465 start = SUFFICIENT_TO_DEOPT_AND_SPECIALIZE
1466 count = start + SUFFICIENT_TO_DEOPT_AND_SPECIALIZE
1467 try:
1468 for i in range(count):
1469 if i == start:
1470 _testinternalcapi.set_eval_frame_record(actual_calls)
1471 func()
1472 finally:
1473 _testinternalcapi.set_eval_frame_default()
1474 expected_calls = names * SUFFICIENT_TO_DEOPT_AND_SPECIALIZE
1475 self.assertEqual(len(expected_calls), len(actual_calls))
1476 for expected, actual in zip(expected_calls, actual_calls, strict=True):
1477 self.assertEqual(expected, actual)
1478
1479 def test_inlined_binary_subscr(self):
1480 class C:
1481 def __getitem__(self, other):
1482 return None
1483 def func():
1484 C()[42]
1485 names = ["func", "__getitem__"]
1486 self.do_test(func, names)
1487
1488 def test_inlined_call(self):
1489 def inner(x=42):
1490 pass
1491 def func():
1492 inner()
1493 inner(42)
1494 names = ["func", "inner", "inner"]
1495 self.do_test(func, names)
1496
1497
1498 if __name__ == "__main__":
1499 unittest.main()