blob: f9578d3afa81f3e67489dd6420998e54d66514d6 [file] [log] [blame]
Tim Petersd66595f2001-02-04 03:09:53 +00001# Run the _testcapi module tests (tests for the Python/C API): by defn,
Guido van Rossum361c5352001-04-13 17:03:04 +00002# these are all functions _testcapi exports whose name begins with 'test_'.
Tim Peters9ea17ac2001-02-02 05:57:15 +00003
Nick Coghlan39f0bb52017-11-28 08:11:51 +10004from collections import OrderedDict
Antoine Pitrou8e605772011-04-25 21:21:07 +02005import os
Antoine Pitrou2f828f22012-01-18 00:21:11 +01006import pickle
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +00007import random
Victor Stinnerb3adb1a2016-03-14 17:40:09 +01008import re
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +00009import subprocess
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +000010import sys
Victor Stinnerefde1462015-03-21 15:04:43 +010011import textwrap
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020012import threading
Benjamin Petersona54c9092009-01-13 02:11:23 +000013import time
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000014import unittest
Eddie Elizondo3368f3c2019-09-19 09:29:05 -070015import weakref
Benjamin Petersonee8712c2008-05-20 21:35:26 +000016from test import support
Larry Hastingsfcafe432013-11-23 17:35:48 -080017from test.support import MISSING_C_DOCSTRINGS
xdegaye85f64302017-07-01 14:14:45 +020018from test.support.script_helper import assert_python_failure, assert_python_ok
Victor Stinner45df8202010-04-28 22:31:17 +000019try:
Stefan Krahfd24f9e2012-08-20 11:04:24 +020020 import _posixsubprocess
21except ImportError:
22 _posixsubprocess = None
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020023
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +020024# Skip this test if the _testcapi module isn't available.
25_testcapi = support.import_module('_testcapi')
Tim Peters9ea17ac2001-02-02 05:57:15 +000026
Victor Stinner1ae035b2020-04-17 17:47:20 +020027import _testinternalcapi
28
Victor Stinnerefde1462015-03-21 15:04:43 +010029# Were we compiled --with-pydebug or with #define Py_DEBUG?
30Py_DEBUG = hasattr(sys, 'gettotalrefcount')
31
Benjamin Petersona54c9092009-01-13 02:11:23 +000032
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000033def testfunction(self):
34 """some doc"""
35 return self
36
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +020037
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000038class InstanceMethod:
39 id = _testcapi.instancemethod(id)
40 testfunction = _testcapi.instancemethod(testfunction)
41
42class CAPITest(unittest.TestCase):
43
44 def test_instancemethod(self):
45 inst = InstanceMethod()
46 self.assertEqual(id(inst), inst.id())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000047 self.assertTrue(inst.testfunction() is inst)
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000048 self.assertEqual(inst.testfunction.__doc__, testfunction.__doc__)
49 self.assertEqual(InstanceMethod.testfunction.__doc__, testfunction.__doc__)
50
51 InstanceMethod.testfunction.attribute = "test"
52 self.assertEqual(testfunction.attribute, "test")
53 self.assertRaises(AttributeError, setattr, inst.testfunction, "attribute", "test")
54
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000055 def test_no_FatalError_infinite_loop(self):
Antoine Pitrou77e904e2013-10-08 23:04:32 +020056 with support.SuppressCrashReport():
Ezio Melotti25a40452013-03-05 20:26:17 +020057 p = subprocess.Popen([sys.executable, "-c",
Ezio Melottie1857d92013-03-05 20:31:34 +020058 'import _testcapi;'
59 '_testcapi.crash_no_current_thread()'],
60 stdout=subprocess.PIPE,
61 stderr=subprocess.PIPE)
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000062 (out, err) = p.communicate()
63 self.assertEqual(out, b'')
64 # This used to cause an infinite loop.
Vinay Sajip73954042012-05-06 11:34:50 +010065 self.assertTrue(err.rstrip().startswith(
Victor Stinner9e5d30c2020-03-07 00:54:20 +010066 b'Fatal Python error: '
Victor Stinner23ef89d2020-03-18 02:26:04 +010067 b'PyThreadState_Get: '
68 b'current thread state is NULL (released GIL?)'))
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000069
Antoine Pitrou915605c2011-02-24 20:53:48 +000070 def test_memoryview_from_NULL_pointer(self):
71 self.assertRaises(ValueError, _testcapi.make_memoryview_from_NULL_pointer)
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000072
Martin v. Löwisaa2efcb2012-04-19 14:33:43 +020073 def test_exc_info(self):
74 raised_exception = ValueError("5")
75 new_exc = TypeError("TEST")
76 try:
77 raise raised_exception
78 except ValueError as e:
79 tb = e.__traceback__
80 orig_sys_exc_info = sys.exc_info()
81 orig_exc_info = _testcapi.set_exc_info(new_exc.__class__, new_exc, None)
82 new_sys_exc_info = sys.exc_info()
83 new_exc_info = _testcapi.set_exc_info(*orig_exc_info)
84 reset_sys_exc_info = sys.exc_info()
85
86 self.assertEqual(orig_exc_info[1], e)
87
88 self.assertSequenceEqual(orig_exc_info, (raised_exception.__class__, raised_exception, tb))
89 self.assertSequenceEqual(orig_sys_exc_info, orig_exc_info)
90 self.assertSequenceEqual(reset_sys_exc_info, orig_exc_info)
91 self.assertSequenceEqual(new_exc_info, (new_exc.__class__, new_exc, None))
92 self.assertSequenceEqual(new_sys_exc_info, new_exc_info)
93 else:
94 self.assertTrue(False)
95
Stefan Krahfd24f9e2012-08-20 11:04:24 +020096 @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
97 def test_seq_bytes_to_charp_array(self):
98 # Issue #15732: crash in _PySequence_BytesToCharpArray()
99 class Z(object):
100 def __len__(self):
101 return 1
102 self.assertRaises(TypeError, _posixsubprocess.fork_exec,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -0700103 1,Z(),3,(1, 2),5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21)
Stefan Krah7cacd2e2012-08-21 08:16:09 +0200104 # Issue #15736: overflow in _PySequence_BytesToCharpArray()
105 class Z(object):
106 def __len__(self):
107 return sys.maxsize
108 def __getitem__(self, i):
109 return b'x'
110 self.assertRaises(MemoryError, _posixsubprocess.fork_exec,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -0700111 1,Z(),3,(1, 2),5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21)
Stefan Krahfd24f9e2012-08-20 11:04:24 +0200112
Stefan Krahdb579d72012-08-20 14:36:47 +0200113 @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
114 def test_subprocess_fork_exec(self):
115 class Z(object):
116 def __len__(self):
117 return 1
118
119 # Issue #15738: crash in subprocess_fork_exec()
120 self.assertRaises(TypeError, _posixsubprocess.fork_exec,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -0700121 Z(),[b'1'],3,(1, 2),5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21)
Stefan Krahdb579d72012-08-20 14:36:47 +0200122
Larry Hastingsfcafe432013-11-23 17:35:48 -0800123 @unittest.skipIf(MISSING_C_DOCSTRINGS,
124 "Signature information for builtins requires docstrings")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800125 def test_docstring_signature_parsing(self):
126
127 self.assertEqual(_testcapi.no_docstring.__doc__, None)
128 self.assertEqual(_testcapi.no_docstring.__text_signature__, None)
129
Zachary Ware8ef887c2015-04-13 18:22:35 -0500130 self.assertEqual(_testcapi.docstring_empty.__doc__, None)
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800131 self.assertEqual(_testcapi.docstring_empty.__text_signature__, None)
132
133 self.assertEqual(_testcapi.docstring_no_signature.__doc__,
134 "This docstring has no signature.")
135 self.assertEqual(_testcapi.docstring_no_signature.__text_signature__, None)
136
137 self.assertEqual(_testcapi.docstring_with_invalid_signature.__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800138 "docstring_with_invalid_signature($module, /, boo)\n"
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800139 "\n"
140 "This docstring has an invalid signature."
141 )
142 self.assertEqual(_testcapi.docstring_with_invalid_signature.__text_signature__, None)
143
Larry Hastings2623c8c2014-02-08 22:15:29 -0800144 self.assertEqual(_testcapi.docstring_with_invalid_signature2.__doc__,
145 "docstring_with_invalid_signature2($module, /, boo)\n"
146 "\n"
147 "--\n"
148 "\n"
149 "This docstring also has an invalid signature."
150 )
151 self.assertEqual(_testcapi.docstring_with_invalid_signature2.__text_signature__, None)
152
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800153 self.assertEqual(_testcapi.docstring_with_signature.__doc__,
154 "This docstring has a valid signature.")
Larry Hastings2623c8c2014-02-08 22:15:29 -0800155 self.assertEqual(_testcapi.docstring_with_signature.__text_signature__, "($module, /, sig)")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800156
Zachary Ware8ef887c2015-04-13 18:22:35 -0500157 self.assertEqual(_testcapi.docstring_with_signature_but_no_doc.__doc__, None)
158 self.assertEqual(_testcapi.docstring_with_signature_but_no_doc.__text_signature__,
159 "($module, /, sig)")
160
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800161 self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800162 "\nThis docstring has a valid signature and some extra newlines.")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800163 self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__text_signature__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800164 "($module, /, parameter)")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800165
Benjamin Petersond51374e2014-04-09 23:55:56 -0400166 def test_c_type_with_matrix_multiplication(self):
167 M = _testcapi.matmulType
168 m1 = M()
169 m2 = M()
170 self.assertEqual(m1 @ m2, ("matmul", m1, m2))
171 self.assertEqual(m1 @ 42, ("matmul", m1, 42))
172 self.assertEqual(42 @ m1, ("matmul", 42, m1))
173 o = m1
174 o @= m2
175 self.assertEqual(o, ("imatmul", m1, m2))
176 o = m1
177 o @= 42
178 self.assertEqual(o, ("imatmul", m1, 42))
179 o = 42
180 o @= m1
181 self.assertEqual(o, ("matmul", 42, m1))
182
Zackery Spytzc7f803b2019-05-31 03:46:36 -0600183 def test_c_type_with_ipow(self):
184 # When the __ipow__ method of a type was implemented in C, using the
185 # modulo param would cause segfaults.
186 o = _testcapi.ipowType()
187 self.assertEqual(o.__ipow__(1), (1, None))
188 self.assertEqual(o.__ipow__(2, 2), (2, 2))
189
Victor Stinnerefde1462015-03-21 15:04:43 +0100190 def test_return_null_without_error(self):
191 # Issue #23571: A function must not return NULL without setting an
192 # error
193 if Py_DEBUG:
194 code = textwrap.dedent("""
195 import _testcapi
196 from test import support
197
198 with support.SuppressCrashReport():
199 _testcapi.return_null_without_error()
200 """)
201 rc, out, err = assert_python_failure('-c', code)
Victor Stinner381a9bc2015-03-24 14:01:32 +0100202 self.assertRegex(err.replace(b'\r', b''),
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100203 br'Fatal Python error: _Py_CheckFunctionResult: '
204 br'a function returned NULL '
Victor Stinner944fbcc2015-03-24 16:28:52 +0100205 br'without setting an error\n'
Victor Stinner1ce16fb2019-09-18 01:35:33 +0200206 br'Python runtime state: initialized\n'
Victor Stinner381a9bc2015-03-24 14:01:32 +0100207 br'SystemError: <built-in function '
208 br'return_null_without_error> returned NULL '
209 br'without setting an error\n'
210 br'\n'
211 br'Current thread.*:\n'
212 br' File .*", line 6 in <module>')
Victor Stinnerefde1462015-03-21 15:04:43 +0100213 else:
214 with self.assertRaises(SystemError) as cm:
215 _testcapi.return_null_without_error()
216 self.assertRegex(str(cm.exception),
217 'return_null_without_error.* '
218 'returned NULL without setting an error')
219
220 def test_return_result_with_error(self):
221 # Issue #23571: A function must not return a result with an error set
222 if Py_DEBUG:
223 code = textwrap.dedent("""
224 import _testcapi
225 from test import support
226
227 with support.SuppressCrashReport():
228 _testcapi.return_result_with_error()
229 """)
230 rc, out, err = assert_python_failure('-c', code)
Victor Stinner381a9bc2015-03-24 14:01:32 +0100231 self.assertRegex(err.replace(b'\r', b''),
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100232 br'Fatal Python error: _Py_CheckFunctionResult: '
233 br'a function returned a result '
234 br'with an error set\n'
Victor Stinner1ce16fb2019-09-18 01:35:33 +0200235 br'Python runtime state: initialized\n'
Victor Stinner381a9bc2015-03-24 14:01:32 +0100236 br'ValueError\n'
237 br'\n'
Serhiy Storchaka467ab192016-10-21 17:09:17 +0300238 br'The above exception was the direct cause '
239 br'of the following exception:\n'
Victor Stinner381a9bc2015-03-24 14:01:32 +0100240 br'\n'
241 br'SystemError: <built-in '
242 br'function return_result_with_error> '
243 br'returned a result with an error set\n'
244 br'\n'
245 br'Current thread.*:\n'
246 br' File .*, line 6 in <module>')
Victor Stinnerefde1462015-03-21 15:04:43 +0100247 else:
248 with self.assertRaises(SystemError) as cm:
249 _testcapi.return_result_with_error()
250 self.assertRegex(str(cm.exception),
251 'return_result_with_error.* '
252 'returned a result with an error set')
253
Serhiy Storchaka13e602e2016-05-20 22:31:14 +0300254 def test_buildvalue_N(self):
255 _testcapi.test_buildvalue_N()
256
xdegaye85f64302017-07-01 14:14:45 +0200257 def test_set_nomemory(self):
258 code = """if 1:
259 import _testcapi
260
261 class C(): pass
262
263 # The first loop tests both functions and that remove_mem_hooks()
264 # can be called twice in a row. The second loop checks a call to
265 # set_nomemory() after a call to remove_mem_hooks(). The third
266 # loop checks the start and stop arguments of set_nomemory().
267 for outer_cnt in range(1, 4):
268 start = 10 * outer_cnt
269 for j in range(100):
270 if j == 0:
271 if outer_cnt != 3:
272 _testcapi.set_nomemory(start)
273 else:
274 _testcapi.set_nomemory(start, start + 1)
275 try:
276 C()
277 except MemoryError as e:
278 if outer_cnt != 3:
279 _testcapi.remove_mem_hooks()
280 print('MemoryError', outer_cnt, j)
281 _testcapi.remove_mem_hooks()
282 break
283 """
284 rc, out, err = assert_python_ok('-c', code)
285 self.assertIn(b'MemoryError 1 10', out)
286 self.assertIn(b'MemoryError 2 20', out)
287 self.assertIn(b'MemoryError 3 30', out)
288
Oren Milman0ccc0f62017-10-08 11:17:46 +0300289 def test_mapping_keys_values_items(self):
290 class Mapping1(dict):
291 def keys(self):
292 return list(super().keys())
293 def values(self):
294 return list(super().values())
295 def items(self):
296 return list(super().items())
297 class Mapping2(dict):
298 def keys(self):
299 return tuple(super().keys())
300 def values(self):
301 return tuple(super().values())
302 def items(self):
303 return tuple(super().items())
304 dict_obj = {'foo': 1, 'bar': 2, 'spam': 3}
305
306 for mapping in [{}, OrderedDict(), Mapping1(), Mapping2(),
307 dict_obj, OrderedDict(dict_obj),
308 Mapping1(dict_obj), Mapping2(dict_obj)]:
309 self.assertListEqual(_testcapi.get_mapping_keys(mapping),
310 list(mapping.keys()))
311 self.assertListEqual(_testcapi.get_mapping_values(mapping),
312 list(mapping.values()))
313 self.assertListEqual(_testcapi.get_mapping_items(mapping),
314 list(mapping.items()))
315
316 def test_mapping_keys_values_items_bad_arg(self):
317 self.assertRaises(AttributeError, _testcapi.get_mapping_keys, None)
318 self.assertRaises(AttributeError, _testcapi.get_mapping_values, None)
319 self.assertRaises(AttributeError, _testcapi.get_mapping_items, None)
320
321 class BadMapping:
322 def keys(self):
323 return None
324 def values(self):
325 return None
326 def items(self):
327 return None
328 bad_mapping = BadMapping()
329 self.assertRaises(TypeError, _testcapi.get_mapping_keys, bad_mapping)
330 self.assertRaises(TypeError, _testcapi.get_mapping_values, bad_mapping)
331 self.assertRaises(TypeError, _testcapi.get_mapping_items, bad_mapping)
332
Victor Stinner18618e652018-10-25 17:28:11 +0200333 @unittest.skipUnless(hasattr(_testcapi, 'negative_refcount'),
334 'need _testcapi.negative_refcount')
335 def test_negative_refcount(self):
336 # bpo-35059: Check that Py_DECREF() reports the correct filename
337 # when calling _Py_NegativeRefcount() to abort Python.
338 code = textwrap.dedent("""
339 import _testcapi
340 from test import support
341
342 with support.SuppressCrashReport():
343 _testcapi.negative_refcount()
344 """)
345 rc, out, err = assert_python_failure('-c', code)
346 self.assertRegex(err,
Victor Stinner3ec9af72018-10-26 02:12:34 +0200347 br'_testcapimodule\.c:[0-9]+: '
Victor Stinnerf1d002c2018-11-21 23:53:44 +0100348 br'_Py_NegativeRefcount: Assertion failed: '
Victor Stinner3ec9af72018-10-26 02:12:34 +0200349 br'object has negative ref count')
Victor Stinner18618e652018-10-25 17:28:11 +0200350
Jeroen Demeyer351c6742019-05-10 19:21:11 +0200351 def test_trashcan_subclass(self):
352 # bpo-35983: Check that the trashcan mechanism for "list" is NOT
353 # activated when its tp_dealloc is being called by a subclass
354 from _testcapi import MyList
355 L = None
356 for i in range(1000):
357 L = MyList((L,))
358
Victor Stinner0127bb12019-11-21 12:54:02 +0100359 @support.requires_resource('cpu')
Jeroen Demeyer351c6742019-05-10 19:21:11 +0200360 def test_trashcan_python_class1(self):
361 self.do_test_trashcan_python_class(list)
362
Victor Stinner0127bb12019-11-21 12:54:02 +0100363 @support.requires_resource('cpu')
Jeroen Demeyer351c6742019-05-10 19:21:11 +0200364 def test_trashcan_python_class2(self):
365 from _testcapi import MyList
366 self.do_test_trashcan_python_class(MyList)
367
368 def do_test_trashcan_python_class(self, base):
369 # Check that the trashcan mechanism works properly for a Python
370 # subclass of a class using the trashcan (this specific test assumes
371 # that the base class "base" behaves like list)
372 class PyList(base):
373 # Count the number of PyList instances to verify that there is
374 # no memory leak
375 num = 0
376 def __init__(self, *args):
377 __class__.num += 1
378 super().__init__(*args)
379 def __del__(self):
380 __class__.num -= 1
381
382 for parity in (0, 1):
383 L = None
384 # We need in the order of 2**20 iterations here such that a
385 # typical 8MB stack would overflow without the trashcan.
386 for i in range(2**20):
387 L = PyList((L,))
388 L.attr = i
389 if parity:
390 # Add one additional nesting layer
391 L = (L,)
392 self.assertGreater(PyList.num, 0)
393 del L
394 self.assertEqual(PyList.num, 0)
395
Eddie Elizondoff023ed2019-09-11 05:17:13 -0400396 def test_subclass_of_heap_gc_ctype_with_tpdealloc_decrefs_once(self):
397 class HeapGcCTypeSubclass(_testcapi.HeapGcCType):
398 def __init__(self):
399 self.value2 = 20
400 super().__init__()
401
402 subclass_instance = HeapGcCTypeSubclass()
403 type_refcnt = sys.getrefcount(HeapGcCTypeSubclass)
404
405 # Test that subclass instance was fully created
406 self.assertEqual(subclass_instance.value, 10)
407 self.assertEqual(subclass_instance.value2, 20)
408
409 # Test that the type reference count is only decremented once
410 del subclass_instance
411 self.assertEqual(type_refcnt - 1, sys.getrefcount(HeapGcCTypeSubclass))
412
413 def test_subclass_of_heap_gc_ctype_with_del_modifying_dunder_class_only_decrefs_once(self):
414 class A(_testcapi.HeapGcCType):
415 def __init__(self):
416 self.value2 = 20
417 super().__init__()
418
419 class B(A):
420 def __init__(self):
421 super().__init__()
422
423 def __del__(self):
424 self.__class__ = A
425 A.refcnt_in_del = sys.getrefcount(A)
426 B.refcnt_in_del = sys.getrefcount(B)
427
428 subclass_instance = B()
429 type_refcnt = sys.getrefcount(B)
430 new_type_refcnt = sys.getrefcount(A)
431
432 # Test that subclass instance was fully created
433 self.assertEqual(subclass_instance.value, 10)
434 self.assertEqual(subclass_instance.value2, 20)
435
436 del subclass_instance
437
438 # Test that setting __class__ modified the reference counts of the types
439 self.assertEqual(type_refcnt - 1, B.refcnt_in_del)
440 self.assertEqual(new_type_refcnt + 1, A.refcnt_in_del)
441
442 # Test that the original type already has decreased its refcnt
443 self.assertEqual(type_refcnt - 1, sys.getrefcount(B))
444
445 # Test that subtype_dealloc decref the newly assigned __class__ only once
446 self.assertEqual(new_type_refcnt, sys.getrefcount(A))
447
Eddie Elizondo3368f3c2019-09-19 09:29:05 -0700448 def test_heaptype_with_dict(self):
449 inst = _testcapi.HeapCTypeWithDict()
450 inst.foo = 42
451 self.assertEqual(inst.foo, 42)
452 self.assertEqual(inst.dictobj, inst.__dict__)
453 self.assertEqual(inst.dictobj, {"foo": 42})
454
455 inst = _testcapi.HeapCTypeWithDict()
456 self.assertEqual({}, inst.__dict__)
457
458 def test_heaptype_with_negative_dict(self):
459 inst = _testcapi.HeapCTypeWithNegativeDict()
460 inst.foo = 42
461 self.assertEqual(inst.foo, 42)
462 self.assertEqual(inst.dictobj, inst.__dict__)
463 self.assertEqual(inst.dictobj, {"foo": 42})
464
465 inst = _testcapi.HeapCTypeWithNegativeDict()
466 self.assertEqual({}, inst.__dict__)
467
468 def test_heaptype_with_weakref(self):
469 inst = _testcapi.HeapCTypeWithWeakref()
470 ref = weakref.ref(inst)
471 self.assertEqual(ref(), inst)
472 self.assertEqual(inst.weakreflist, ref)
473
Eddie Elizondoff023ed2019-09-11 05:17:13 -0400474 def test_c_subclass_of_heap_ctype_with_tpdealloc_decrefs_once(self):
475 subclass_instance = _testcapi.HeapCTypeSubclass()
476 type_refcnt = sys.getrefcount(_testcapi.HeapCTypeSubclass)
477
478 # Test that subclass instance was fully created
479 self.assertEqual(subclass_instance.value, 10)
480 self.assertEqual(subclass_instance.value2, 20)
481
482 # Test that the type reference count is only decremented once
483 del subclass_instance
484 self.assertEqual(type_refcnt - 1, sys.getrefcount(_testcapi.HeapCTypeSubclass))
485
486 def test_c_subclass_of_heap_ctype_with_del_modifying_dunder_class_only_decrefs_once(self):
487 subclass_instance = _testcapi.HeapCTypeSubclassWithFinalizer()
488 type_refcnt = sys.getrefcount(_testcapi.HeapCTypeSubclassWithFinalizer)
489 new_type_refcnt = sys.getrefcount(_testcapi.HeapCTypeSubclass)
490
491 # Test that subclass instance was fully created
492 self.assertEqual(subclass_instance.value, 10)
493 self.assertEqual(subclass_instance.value2, 20)
494
495 # The tp_finalize slot will set __class__ to HeapCTypeSubclass
496 del subclass_instance
497
498 # Test that setting __class__ modified the reference counts of the types
499 self.assertEqual(type_refcnt - 1, _testcapi.HeapCTypeSubclassWithFinalizer.refcnt_in_del)
500 self.assertEqual(new_type_refcnt + 1, _testcapi.HeapCTypeSubclass.refcnt_in_del)
501
502 # Test that the original type already has decreased its refcnt
503 self.assertEqual(type_refcnt - 1, sys.getrefcount(_testcapi.HeapCTypeSubclassWithFinalizer))
504
505 # Test that subtype_dealloc decref the newly assigned __class__ only once
506 self.assertEqual(new_type_refcnt, sys.getrefcount(_testcapi.HeapCTypeSubclass))
507
Serhiy Storchakae5ccc942020-03-09 20:03:38 +0200508 def test_pynumber_tobase(self):
509 from _testcapi import pynumber_tobase
510 self.assertEqual(pynumber_tobase(123, 2), '0b1111011')
511 self.assertEqual(pynumber_tobase(123, 8), '0o173')
512 self.assertEqual(pynumber_tobase(123, 10), '123')
513 self.assertEqual(pynumber_tobase(123, 16), '0x7b')
514 self.assertEqual(pynumber_tobase(-123, 2), '-0b1111011')
515 self.assertEqual(pynumber_tobase(-123, 8), '-0o173')
516 self.assertEqual(pynumber_tobase(-123, 10), '-123')
517 self.assertEqual(pynumber_tobase(-123, 16), '-0x7b')
518 self.assertRaises(TypeError, pynumber_tobase, 123.0, 10)
519 self.assertRaises(TypeError, pynumber_tobase, '123', 10)
520 self.assertRaises(SystemError, pynumber_tobase, 123, 0)
521
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800522
Benjamin Petersona54c9092009-01-13 02:11:23 +0000523class TestPendingCalls(unittest.TestCase):
524
525 def pendingcalls_submit(self, l, n):
526 def callback():
527 #this function can be interrupted by thread switching so let's
528 #use an atomic operation
529 l.append(None)
530
531 for i in range(n):
532 time.sleep(random.random()*0.02) #0.01 secs on average
533 #try submitting callback until successful.
534 #rely on regular interrupt to flush queue if we are
535 #unsuccessful.
536 while True:
537 if _testcapi._pending_threadfunc(callback):
538 break;
539
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000540 def pendingcalls_wait(self, l, n, context = None):
Benjamin Petersona54c9092009-01-13 02:11:23 +0000541 #now, stick around until l[0] has grown to 10
542 count = 0;
543 while len(l) != n:
544 #this busy loop is where we expect to be interrupted to
545 #run our callbacks. Note that callbacks are only run on the
546 #main thread
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000547 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +0000548 print("(%i)"%(len(l),),)
549 for i in range(1000):
550 a = i*i
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000551 if context and not context.event.is_set():
552 continue
Benjamin Petersona54c9092009-01-13 02:11:23 +0000553 count += 1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000554 self.assertTrue(count < 10000,
Benjamin Petersona54c9092009-01-13 02:11:23 +0000555 "timeout waiting for %i callbacks, got %i"%(n, len(l)))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000556 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +0000557 print("(%i)"%(len(l),))
558
559 def test_pendingcalls_threaded(self):
Benjamin Petersona54c9092009-01-13 02:11:23 +0000560
561 #do every callback on a separate thread
Victor Stinnere225beb2019-06-03 18:14:24 +0200562 n = 32 #total callbacks
Benjamin Petersona54c9092009-01-13 02:11:23 +0000563 threads = []
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000564 class foo(object):pass
565 context = foo()
566 context.l = []
567 context.n = 2 #submits per thread
568 context.nThreads = n // context.n
569 context.nFinished = 0
570 context.lock = threading.Lock()
571 context.event = threading.Event()
572
Serhiy Storchaka263dcd22015-04-01 13:01:14 +0300573 threads = [threading.Thread(target=self.pendingcalls_thread,
574 args=(context,))
575 for i in range(context.nThreads)]
576 with support.start_threads(threads):
577 self.pendingcalls_wait(context.l, n, context)
Benjamin Petersona54c9092009-01-13 02:11:23 +0000578
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000579 def pendingcalls_thread(self, context):
580 try:
581 self.pendingcalls_submit(context.l, context.n)
582 finally:
583 with context.lock:
584 context.nFinished += 1
585 nFinished = context.nFinished
586 if False and support.verbose:
587 print("finished threads: ", nFinished)
588 if nFinished == context.nThreads:
589 context.event.set()
590
Benjamin Petersona54c9092009-01-13 02:11:23 +0000591 def test_pendingcalls_non_threaded(self):
Ezio Melotti13925002011-03-16 11:05:33 +0200592 #again, just using the main thread, likely they will all be dispatched at
Benjamin Petersona54c9092009-01-13 02:11:23 +0000593 #once. It is ok to ask for too many, because we loop until we find a slot.
594 #the loop can be interrupted to dispatch.
595 #there are only 32 dispatch slots, so we go for twice that!
596 l = []
597 n = 64
598 self.pendingcalls_submit(l, n)
599 self.pendingcalls_wait(l, n)
600
Antoine Pitrou7a2572c2013-08-01 20:43:26 +0200601
602class SubinterpreterTest(unittest.TestCase):
603
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100604 def test_subinterps(self):
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100605 import builtins
606 r, w = os.pipe()
607 code = """if 1:
608 import sys, builtins, pickle
609 with open({:d}, "wb") as f:
610 pickle.dump(id(sys.modules), f)
611 pickle.dump(id(builtins), f)
612 """.format(w)
613 with open(r, "rb") as f:
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100614 ret = support.run_in_subinterp(code)
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100615 self.assertEqual(ret, 0)
616 self.assertNotEqual(pickle.load(f), id(sys.modules))
617 self.assertNotEqual(pickle.load(f), id(builtins))
618
Marcel Plch33e71e02019-05-22 13:51:26 +0200619 def test_mutate_exception(self):
620 """
621 Exceptions saved in global module state get shared between
622 individual module instances. This test checks whether or not
623 a change in one interpreter's module gets reflected into the
624 other ones.
625 """
626 import binascii
627
628 support.run_in_subinterp("import binascii; binascii.Error.foobar = 'foobar'")
629
630 self.assertFalse(hasattr(binascii.Error, "foobar"))
631
Antoine Pitrou7a2572c2013-08-01 20:43:26 +0200632
Ezio Melotti29267c82013-02-23 05:52:46 +0200633class TestThreadState(unittest.TestCase):
634
635 @support.reap_threads
636 def test_thread_state(self):
637 # some extra thread-state tests driven via _testcapi
638 def target():
639 idents = []
640
641 def callback():
Ezio Melotti35246bd2013-02-23 05:58:38 +0200642 idents.append(threading.get_ident())
Ezio Melotti29267c82013-02-23 05:52:46 +0200643
644 _testcapi._test_thread_state(callback)
645 a = b = callback
646 time.sleep(1)
647 # Check our main thread is in the list exactly 3 times.
Ezio Melotti35246bd2013-02-23 05:58:38 +0200648 self.assertEqual(idents.count(threading.get_ident()), 3,
Ezio Melotti29267c82013-02-23 05:52:46 +0200649 "Couldn't find main thread correctly in the list")
650
651 target()
652 t = threading.Thread(target=target)
653 t.start()
654 t.join()
655
Victor Stinner34be8072016-03-14 12:04:26 +0100656
Zachary Warec12f09e2013-11-11 22:47:04 -0600657class Test_testcapi(unittest.TestCase):
Serhiy Storchaka8f7bb102018-08-06 16:50:19 +0300658 locals().update((name, getattr(_testcapi, name))
659 for name in dir(_testcapi)
660 if name.startswith('test_') and not name.endswith('_code'))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000661
Victor Stinner34be8072016-03-14 12:04:26 +0100662
Victor Stinner1ae035b2020-04-17 17:47:20 +0200663class Test_testinternalcapi(unittest.TestCase):
664 locals().update((name, getattr(_testinternalcapi, name))
665 for name in dir(_testinternalcapi)
666 if name.startswith('test_'))
667
668
Victor Stinnerc4aec362016-03-14 22:26:53 +0100669class PyMemDebugTests(unittest.TestCase):
670 PYTHONMALLOC = 'debug'
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100671 # '0x04c06e0' or '04C06E0'
Victor Stinner08572f62016-03-14 21:55:43 +0100672 PTR_REGEX = r'(?:0x)?[0-9a-fA-F]+'
Victor Stinner34be8072016-03-14 12:04:26 +0100673
674 def check(self, code):
675 with support.SuppressCrashReport():
Victor Stinnerc4aec362016-03-14 22:26:53 +0100676 out = assert_python_failure('-c', code,
677 PYTHONMALLOC=self.PYTHONMALLOC)
Victor Stinner34be8072016-03-14 12:04:26 +0100678 stderr = out.err
679 return stderr.decode('ascii', 'replace')
680
681 def test_buffer_overflow(self):
682 out = self.check('import _testcapi; _testcapi.pymem_buffer_overflow()')
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100683 regex = (r"Debug memory block at address p={ptr}: API 'm'\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100684 r" 16 bytes originally requested\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100685 r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n"
686 r" The [0-9] pad bytes at tail={ptr} are not all FORBIDDENBYTE \(0x[0-9a-f]{{2}}\):\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100687 r" at tail\+0: 0x78 \*\*\* OUCH\n"
Victor Stinner4c409be2019-04-11 13:01:15 +0200688 r" at tail\+1: 0xfd\n"
689 r" at tail\+2: 0xfd\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100690 r" .*\n"
Victor Stinnere8f9acf2019-04-12 21:54:06 +0200691 r"( The block was made by call #[0-9]+ to debug malloc/realloc.\n)?"
Victor Stinner4c409be2019-04-11 13:01:15 +0200692 r" Data at p: cd cd cd .*\n"
Victor Stinner6453e9e2016-03-15 23:36:28 +0100693 r"\n"
Victor Stinnerf966e532018-11-13 15:14:58 +0100694 r"Enable tracemalloc to get the memory block allocation traceback\n"
695 r"\n"
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100696 r"Fatal Python error: _PyMem_DebugRawFree: bad trailing pad byte")
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100697 regex = regex.format(ptr=self.PTR_REGEX)
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100698 regex = re.compile(regex, flags=re.DOTALL)
Victor Stinner34be8072016-03-14 12:04:26 +0100699 self.assertRegex(out, regex)
700
701 def test_api_misuse(self):
702 out = self.check('import _testcapi; _testcapi.pymem_api_misuse()')
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100703 regex = (r"Debug memory block at address p={ptr}: API 'm'\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100704 r" 16 bytes originally requested\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100705 r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n"
706 r" The [0-9] pad bytes at tail={ptr} are FORBIDDENBYTE, as expected.\n"
Victor Stinnere8f9acf2019-04-12 21:54:06 +0200707 r"( The block was made by call #[0-9]+ to debug malloc/realloc.\n)?"
Victor Stinner4c409be2019-04-11 13:01:15 +0200708 r" Data at p: cd cd cd .*\n"
Victor Stinner6453e9e2016-03-15 23:36:28 +0100709 r"\n"
Victor Stinnerf966e532018-11-13 15:14:58 +0100710 r"Enable tracemalloc to get the memory block allocation traceback\n"
711 r"\n"
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100712 r"Fatal Python error: _PyMem_DebugRawFree: bad ID: Allocated using API 'm', verified using API 'r'\n")
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100713 regex = regex.format(ptr=self.PTR_REGEX)
Victor Stinner34be8072016-03-14 12:04:26 +0100714 self.assertRegex(out, regex)
715
Victor Stinnerad524372016-03-16 12:12:53 +0100716 def check_malloc_without_gil(self, code):
Victor Stinnerc4aec362016-03-14 22:26:53 +0100717 out = self.check(code)
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100718 expected = ('Fatal Python error: _PyMem_DebugMalloc: '
719 'Python memory allocator called without holding the GIL')
Victor Stinnerc4aec362016-03-14 22:26:53 +0100720 self.assertIn(expected, out)
Victor Stinner34be8072016-03-14 12:04:26 +0100721
Victor Stinnerad524372016-03-16 12:12:53 +0100722 def test_pymem_malloc_without_gil(self):
723 # Debug hooks must raise an error if PyMem_Malloc() is called
724 # without holding the GIL
725 code = 'import _testcapi; _testcapi.pymem_malloc_without_gil()'
726 self.check_malloc_without_gil(code)
727
728 def test_pyobject_malloc_without_gil(self):
729 # Debug hooks must raise an error if PyObject_Malloc() is called
730 # without holding the GIL
731 code = 'import _testcapi; _testcapi.pyobject_malloc_without_gil()'
732 self.check_malloc_without_gil(code)
733
Victor Stinner3bf0f3a2019-06-07 16:22:21 +0200734 def check_pyobject_is_freed(self, func_name):
735 code = textwrap.dedent(f'''
Victor Stinner2b00db62019-04-11 11:33:27 +0200736 import gc, os, sys, _testcapi
737 # Disable the GC to avoid crash on GC collection
738 gc.disable()
Victor Stinner3bf0f3a2019-06-07 16:22:21 +0200739 try:
740 _testcapi.{func_name}()
741 # Exit immediately to avoid a crash while deallocating
742 # the invalid object
743 os._exit(0)
744 except _testcapi.error:
745 os._exit(1)
Victor Stinner2b00db62019-04-11 11:33:27 +0200746 ''')
Victor Stinner2b00db62019-04-11 11:33:27 +0200747 assert_python_ok('-c', code, PYTHONMALLOC=self.PYTHONMALLOC)
748
Victor Stinner68762572019-10-07 18:42:01 +0200749 def test_pyobject_null_is_freed(self):
750 self.check_pyobject_is_freed('check_pyobject_null_is_freed')
751
Victor Stinner3bf0f3a2019-06-07 16:22:21 +0200752 def test_pyobject_uninitialized_is_freed(self):
753 self.check_pyobject_is_freed('check_pyobject_uninitialized_is_freed')
Victor Stinner2b00db62019-04-11 11:33:27 +0200754
Victor Stinner3bf0f3a2019-06-07 16:22:21 +0200755 def test_pyobject_forbidden_bytes_is_freed(self):
756 self.check_pyobject_is_freed('check_pyobject_forbidden_bytes_is_freed')
Victor Stinner2b00db62019-04-11 11:33:27 +0200757
Victor Stinner3bf0f3a2019-06-07 16:22:21 +0200758 def test_pyobject_freed_is_freed(self):
759 self.check_pyobject_is_freed('check_pyobject_freed_is_freed')
Victor Stinner2b00db62019-04-11 11:33:27 +0200760
Victor Stinnerc4aec362016-03-14 22:26:53 +0100761
762class PyMemMallocDebugTests(PyMemDebugTests):
763 PYTHONMALLOC = 'malloc_debug'
Victor Stinner34be8072016-03-14 12:04:26 +0100764
765
Victor Stinner5d39e042017-11-29 17:20:38 +0100766@unittest.skipUnless(support.with_pymalloc(), 'need pymalloc')
Victor Stinnerc4aec362016-03-14 22:26:53 +0100767class PyMemPymallocDebugTests(PyMemDebugTests):
768 PYTHONMALLOC = 'pymalloc_debug'
Victor Stinner34be8072016-03-14 12:04:26 +0100769
770
771@unittest.skipUnless(Py_DEBUG, 'need Py_DEBUG')
Victor Stinnerc4aec362016-03-14 22:26:53 +0100772class PyMemDefaultTests(PyMemDebugTests):
773 # test default allocator of Python compiled in debug mode
774 PYTHONMALLOC = ''
Victor Stinner34be8072016-03-14 12:04:26 +0100775
776
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000777if __name__ == "__main__":
Zachary Warec12f09e2013-11-11 22:47:04 -0600778 unittest.main()