blob: e65973c4646b16106b628b97c9a3eb5d918fcc5b [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 Stinnerefde1462015-03-21 15:04:43 +010027# Were we compiled --with-pydebug or with #define Py_DEBUG?
28Py_DEBUG = hasattr(sys, 'gettotalrefcount')
29
Benjamin Petersona54c9092009-01-13 02:11:23 +000030
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000031def testfunction(self):
32 """some doc"""
33 return self
34
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +020035
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000036class InstanceMethod:
37 id = _testcapi.instancemethod(id)
38 testfunction = _testcapi.instancemethod(testfunction)
39
40class CAPITest(unittest.TestCase):
41
42 def test_instancemethod(self):
43 inst = InstanceMethod()
44 self.assertEqual(id(inst), inst.id())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000045 self.assertTrue(inst.testfunction() is inst)
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000046 self.assertEqual(inst.testfunction.__doc__, testfunction.__doc__)
47 self.assertEqual(InstanceMethod.testfunction.__doc__, testfunction.__doc__)
48
49 InstanceMethod.testfunction.attribute = "test"
50 self.assertEqual(testfunction.attribute, "test")
51 self.assertRaises(AttributeError, setattr, inst.testfunction, "attribute", "test")
52
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000053 def test_no_FatalError_infinite_loop(self):
Antoine Pitrou77e904e2013-10-08 23:04:32 +020054 with support.SuppressCrashReport():
Ezio Melotti25a40452013-03-05 20:26:17 +020055 p = subprocess.Popen([sys.executable, "-c",
Ezio Melottie1857d92013-03-05 20:31:34 +020056 'import _testcapi;'
57 '_testcapi.crash_no_current_thread()'],
58 stdout=subprocess.PIPE,
59 stderr=subprocess.PIPE)
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000060 (out, err) = p.communicate()
61 self.assertEqual(out, b'')
62 # This used to cause an infinite loop.
Vinay Sajip73954042012-05-06 11:34:50 +010063 self.assertTrue(err.rstrip().startswith(
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000064 b'Fatal Python error:'
Vinay Sajip73954042012-05-06 11:34:50 +010065 b' PyThreadState_Get: no current thread'))
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000066
Antoine Pitrou915605c2011-02-24 20:53:48 +000067 def test_memoryview_from_NULL_pointer(self):
68 self.assertRaises(ValueError, _testcapi.make_memoryview_from_NULL_pointer)
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000069
Martin v. Löwisaa2efcb2012-04-19 14:33:43 +020070 def test_exc_info(self):
71 raised_exception = ValueError("5")
72 new_exc = TypeError("TEST")
73 try:
74 raise raised_exception
75 except ValueError as e:
76 tb = e.__traceback__
77 orig_sys_exc_info = sys.exc_info()
78 orig_exc_info = _testcapi.set_exc_info(new_exc.__class__, new_exc, None)
79 new_sys_exc_info = sys.exc_info()
80 new_exc_info = _testcapi.set_exc_info(*orig_exc_info)
81 reset_sys_exc_info = sys.exc_info()
82
83 self.assertEqual(orig_exc_info[1], e)
84
85 self.assertSequenceEqual(orig_exc_info, (raised_exception.__class__, raised_exception, tb))
86 self.assertSequenceEqual(orig_sys_exc_info, orig_exc_info)
87 self.assertSequenceEqual(reset_sys_exc_info, orig_exc_info)
88 self.assertSequenceEqual(new_exc_info, (new_exc.__class__, new_exc, None))
89 self.assertSequenceEqual(new_sys_exc_info, new_exc_info)
90 else:
91 self.assertTrue(False)
92
Stefan Krahfd24f9e2012-08-20 11:04:24 +020093 @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
94 def test_seq_bytes_to_charp_array(self):
95 # Issue #15732: crash in _PySequence_BytesToCharpArray()
96 class Z(object):
97 def __len__(self):
98 return 1
99 self.assertRaises(TypeError, _posixsubprocess.fork_exec,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -0700100 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 +0200101 # Issue #15736: overflow in _PySequence_BytesToCharpArray()
102 class Z(object):
103 def __len__(self):
104 return sys.maxsize
105 def __getitem__(self, i):
106 return b'x'
107 self.assertRaises(MemoryError, _posixsubprocess.fork_exec,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -0700108 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 +0200109
Stefan Krahdb579d72012-08-20 14:36:47 +0200110 @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
111 def test_subprocess_fork_exec(self):
112 class Z(object):
113 def __len__(self):
114 return 1
115
116 # Issue #15738: crash in subprocess_fork_exec()
117 self.assertRaises(TypeError, _posixsubprocess.fork_exec,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -0700118 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 +0200119
Larry Hastingsfcafe432013-11-23 17:35:48 -0800120 @unittest.skipIf(MISSING_C_DOCSTRINGS,
121 "Signature information for builtins requires docstrings")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800122 def test_docstring_signature_parsing(self):
123
124 self.assertEqual(_testcapi.no_docstring.__doc__, None)
125 self.assertEqual(_testcapi.no_docstring.__text_signature__, None)
126
Zachary Ware8ef887c2015-04-13 18:22:35 -0500127 self.assertEqual(_testcapi.docstring_empty.__doc__, None)
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800128 self.assertEqual(_testcapi.docstring_empty.__text_signature__, None)
129
130 self.assertEqual(_testcapi.docstring_no_signature.__doc__,
131 "This docstring has no signature.")
132 self.assertEqual(_testcapi.docstring_no_signature.__text_signature__, None)
133
134 self.assertEqual(_testcapi.docstring_with_invalid_signature.__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800135 "docstring_with_invalid_signature($module, /, boo)\n"
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800136 "\n"
137 "This docstring has an invalid signature."
138 )
139 self.assertEqual(_testcapi.docstring_with_invalid_signature.__text_signature__, None)
140
Larry Hastings2623c8c2014-02-08 22:15:29 -0800141 self.assertEqual(_testcapi.docstring_with_invalid_signature2.__doc__,
142 "docstring_with_invalid_signature2($module, /, boo)\n"
143 "\n"
144 "--\n"
145 "\n"
146 "This docstring also has an invalid signature."
147 )
148 self.assertEqual(_testcapi.docstring_with_invalid_signature2.__text_signature__, None)
149
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800150 self.assertEqual(_testcapi.docstring_with_signature.__doc__,
151 "This docstring has a valid signature.")
Larry Hastings2623c8c2014-02-08 22:15:29 -0800152 self.assertEqual(_testcapi.docstring_with_signature.__text_signature__, "($module, /, sig)")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800153
Zachary Ware8ef887c2015-04-13 18:22:35 -0500154 self.assertEqual(_testcapi.docstring_with_signature_but_no_doc.__doc__, None)
155 self.assertEqual(_testcapi.docstring_with_signature_but_no_doc.__text_signature__,
156 "($module, /, sig)")
157
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800158 self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800159 "\nThis docstring has a valid signature and some extra newlines.")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800160 self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__text_signature__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800161 "($module, /, parameter)")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800162
Benjamin Petersond51374e2014-04-09 23:55:56 -0400163 def test_c_type_with_matrix_multiplication(self):
164 M = _testcapi.matmulType
165 m1 = M()
166 m2 = M()
167 self.assertEqual(m1 @ m2, ("matmul", m1, m2))
168 self.assertEqual(m1 @ 42, ("matmul", m1, 42))
169 self.assertEqual(42 @ m1, ("matmul", 42, m1))
170 o = m1
171 o @= m2
172 self.assertEqual(o, ("imatmul", m1, m2))
173 o = m1
174 o @= 42
175 self.assertEqual(o, ("imatmul", m1, 42))
176 o = 42
177 o @= m1
178 self.assertEqual(o, ("matmul", 42, m1))
179
Zackery Spytzc7f803b2019-05-31 03:46:36 -0600180 def test_c_type_with_ipow(self):
181 # When the __ipow__ method of a type was implemented in C, using the
182 # modulo param would cause segfaults.
183 o = _testcapi.ipowType()
184 self.assertEqual(o.__ipow__(1), (1, None))
185 self.assertEqual(o.__ipow__(2, 2), (2, 2))
186
Victor Stinnerefde1462015-03-21 15:04:43 +0100187 def test_return_null_without_error(self):
188 # Issue #23571: A function must not return NULL without setting an
189 # error
190 if Py_DEBUG:
191 code = textwrap.dedent("""
192 import _testcapi
193 from test import support
194
195 with support.SuppressCrashReport():
196 _testcapi.return_null_without_error()
197 """)
198 rc, out, err = assert_python_failure('-c', code)
Victor Stinner381a9bc2015-03-24 14:01:32 +0100199 self.assertRegex(err.replace(b'\r', b''),
Victor Stinner944fbcc2015-03-24 16:28:52 +0100200 br'Fatal Python error: a function returned NULL '
201 br'without setting an error\n'
Victor Stinner1ce16fb2019-09-18 01:35:33 +0200202 br'Python runtime state: initialized\n'
Victor Stinner381a9bc2015-03-24 14:01:32 +0100203 br'SystemError: <built-in function '
204 br'return_null_without_error> returned NULL '
205 br'without setting an error\n'
206 br'\n'
207 br'Current thread.*:\n'
208 br' File .*", line 6 in <module>')
Victor Stinnerefde1462015-03-21 15:04:43 +0100209 else:
210 with self.assertRaises(SystemError) as cm:
211 _testcapi.return_null_without_error()
212 self.assertRegex(str(cm.exception),
213 'return_null_without_error.* '
214 'returned NULL without setting an error')
215
216 def test_return_result_with_error(self):
217 # Issue #23571: A function must not return a result with an error set
218 if Py_DEBUG:
219 code = textwrap.dedent("""
220 import _testcapi
221 from test import support
222
223 with support.SuppressCrashReport():
224 _testcapi.return_result_with_error()
225 """)
226 rc, out, err = assert_python_failure('-c', code)
Victor Stinner381a9bc2015-03-24 14:01:32 +0100227 self.assertRegex(err.replace(b'\r', b''),
Victor Stinner944fbcc2015-03-24 16:28:52 +0100228 br'Fatal Python error: a function returned a '
229 br'result with an error set\n'
Victor Stinner1ce16fb2019-09-18 01:35:33 +0200230 br'Python runtime state: initialized\n'
Victor Stinner381a9bc2015-03-24 14:01:32 +0100231 br'ValueError\n'
232 br'\n'
Serhiy Storchaka467ab192016-10-21 17:09:17 +0300233 br'The above exception was the direct cause '
234 br'of the following exception:\n'
Victor Stinner381a9bc2015-03-24 14:01:32 +0100235 br'\n'
236 br'SystemError: <built-in '
237 br'function return_result_with_error> '
238 br'returned a result with an error set\n'
239 br'\n'
240 br'Current thread.*:\n'
241 br' File .*, line 6 in <module>')
Victor Stinnerefde1462015-03-21 15:04:43 +0100242 else:
243 with self.assertRaises(SystemError) as cm:
244 _testcapi.return_result_with_error()
245 self.assertRegex(str(cm.exception),
246 'return_result_with_error.* '
247 'returned a result with an error set')
248
Serhiy Storchaka13e602e2016-05-20 22:31:14 +0300249 def test_buildvalue_N(self):
250 _testcapi.test_buildvalue_N()
251
xdegaye85f64302017-07-01 14:14:45 +0200252 def test_set_nomemory(self):
253 code = """if 1:
254 import _testcapi
255
256 class C(): pass
257
258 # The first loop tests both functions and that remove_mem_hooks()
259 # can be called twice in a row. The second loop checks a call to
260 # set_nomemory() after a call to remove_mem_hooks(). The third
261 # loop checks the start and stop arguments of set_nomemory().
262 for outer_cnt in range(1, 4):
263 start = 10 * outer_cnt
264 for j in range(100):
265 if j == 0:
266 if outer_cnt != 3:
267 _testcapi.set_nomemory(start)
268 else:
269 _testcapi.set_nomemory(start, start + 1)
270 try:
271 C()
272 except MemoryError as e:
273 if outer_cnt != 3:
274 _testcapi.remove_mem_hooks()
275 print('MemoryError', outer_cnt, j)
276 _testcapi.remove_mem_hooks()
277 break
278 """
279 rc, out, err = assert_python_ok('-c', code)
280 self.assertIn(b'MemoryError 1 10', out)
281 self.assertIn(b'MemoryError 2 20', out)
282 self.assertIn(b'MemoryError 3 30', out)
283
Oren Milman0ccc0f62017-10-08 11:17:46 +0300284 def test_mapping_keys_values_items(self):
285 class Mapping1(dict):
286 def keys(self):
287 return list(super().keys())
288 def values(self):
289 return list(super().values())
290 def items(self):
291 return list(super().items())
292 class Mapping2(dict):
293 def keys(self):
294 return tuple(super().keys())
295 def values(self):
296 return tuple(super().values())
297 def items(self):
298 return tuple(super().items())
299 dict_obj = {'foo': 1, 'bar': 2, 'spam': 3}
300
301 for mapping in [{}, OrderedDict(), Mapping1(), Mapping2(),
302 dict_obj, OrderedDict(dict_obj),
303 Mapping1(dict_obj), Mapping2(dict_obj)]:
304 self.assertListEqual(_testcapi.get_mapping_keys(mapping),
305 list(mapping.keys()))
306 self.assertListEqual(_testcapi.get_mapping_values(mapping),
307 list(mapping.values()))
308 self.assertListEqual(_testcapi.get_mapping_items(mapping),
309 list(mapping.items()))
310
311 def test_mapping_keys_values_items_bad_arg(self):
312 self.assertRaises(AttributeError, _testcapi.get_mapping_keys, None)
313 self.assertRaises(AttributeError, _testcapi.get_mapping_values, None)
314 self.assertRaises(AttributeError, _testcapi.get_mapping_items, None)
315
316 class BadMapping:
317 def keys(self):
318 return None
319 def values(self):
320 return None
321 def items(self):
322 return None
323 bad_mapping = BadMapping()
324 self.assertRaises(TypeError, _testcapi.get_mapping_keys, bad_mapping)
325 self.assertRaises(TypeError, _testcapi.get_mapping_values, bad_mapping)
326 self.assertRaises(TypeError, _testcapi.get_mapping_items, bad_mapping)
327
Victor Stinner18618e652018-10-25 17:28:11 +0200328 @unittest.skipUnless(hasattr(_testcapi, 'negative_refcount'),
329 'need _testcapi.negative_refcount')
330 def test_negative_refcount(self):
331 # bpo-35059: Check that Py_DECREF() reports the correct filename
332 # when calling _Py_NegativeRefcount() to abort Python.
333 code = textwrap.dedent("""
334 import _testcapi
335 from test import support
336
337 with support.SuppressCrashReport():
338 _testcapi.negative_refcount()
339 """)
340 rc, out, err = assert_python_failure('-c', code)
341 self.assertRegex(err,
Victor Stinner3ec9af72018-10-26 02:12:34 +0200342 br'_testcapimodule\.c:[0-9]+: '
Victor Stinnerf1d002c2018-11-21 23:53:44 +0100343 br'_Py_NegativeRefcount: Assertion failed: '
Victor Stinner3ec9af72018-10-26 02:12:34 +0200344 br'object has negative ref count')
Victor Stinner18618e652018-10-25 17:28:11 +0200345
Jeroen Demeyer351c6742019-05-10 19:21:11 +0200346 def test_trashcan_subclass(self):
347 # bpo-35983: Check that the trashcan mechanism for "list" is NOT
348 # activated when its tp_dealloc is being called by a subclass
349 from _testcapi import MyList
350 L = None
351 for i in range(1000):
352 L = MyList((L,))
353
Victor Stinner0127bb12019-11-21 12:54:02 +0100354 @support.requires_resource('cpu')
Jeroen Demeyer351c6742019-05-10 19:21:11 +0200355 def test_trashcan_python_class1(self):
356 self.do_test_trashcan_python_class(list)
357
Victor Stinner0127bb12019-11-21 12:54:02 +0100358 @support.requires_resource('cpu')
Jeroen Demeyer351c6742019-05-10 19:21:11 +0200359 def test_trashcan_python_class2(self):
360 from _testcapi import MyList
361 self.do_test_trashcan_python_class(MyList)
362
363 def do_test_trashcan_python_class(self, base):
364 # Check that the trashcan mechanism works properly for a Python
365 # subclass of a class using the trashcan (this specific test assumes
366 # that the base class "base" behaves like list)
367 class PyList(base):
368 # Count the number of PyList instances to verify that there is
369 # no memory leak
370 num = 0
371 def __init__(self, *args):
372 __class__.num += 1
373 super().__init__(*args)
374 def __del__(self):
375 __class__.num -= 1
376
377 for parity in (0, 1):
378 L = None
379 # We need in the order of 2**20 iterations here such that a
380 # typical 8MB stack would overflow without the trashcan.
381 for i in range(2**20):
382 L = PyList((L,))
383 L.attr = i
384 if parity:
385 # Add one additional nesting layer
386 L = (L,)
387 self.assertGreater(PyList.num, 0)
388 del L
389 self.assertEqual(PyList.num, 0)
390
Eddie Elizondoff023ed2019-09-11 05:17:13 -0400391 def test_subclass_of_heap_gc_ctype_with_tpdealloc_decrefs_once(self):
392 class HeapGcCTypeSubclass(_testcapi.HeapGcCType):
393 def __init__(self):
394 self.value2 = 20
395 super().__init__()
396
397 subclass_instance = HeapGcCTypeSubclass()
398 type_refcnt = sys.getrefcount(HeapGcCTypeSubclass)
399
400 # Test that subclass instance was fully created
401 self.assertEqual(subclass_instance.value, 10)
402 self.assertEqual(subclass_instance.value2, 20)
403
404 # Test that the type reference count is only decremented once
405 del subclass_instance
406 self.assertEqual(type_refcnt - 1, sys.getrefcount(HeapGcCTypeSubclass))
407
408 def test_subclass_of_heap_gc_ctype_with_del_modifying_dunder_class_only_decrefs_once(self):
409 class A(_testcapi.HeapGcCType):
410 def __init__(self):
411 self.value2 = 20
412 super().__init__()
413
414 class B(A):
415 def __init__(self):
416 super().__init__()
417
418 def __del__(self):
419 self.__class__ = A
420 A.refcnt_in_del = sys.getrefcount(A)
421 B.refcnt_in_del = sys.getrefcount(B)
422
423 subclass_instance = B()
424 type_refcnt = sys.getrefcount(B)
425 new_type_refcnt = sys.getrefcount(A)
426
427 # Test that subclass instance was fully created
428 self.assertEqual(subclass_instance.value, 10)
429 self.assertEqual(subclass_instance.value2, 20)
430
431 del subclass_instance
432
433 # Test that setting __class__ modified the reference counts of the types
434 self.assertEqual(type_refcnt - 1, B.refcnt_in_del)
435 self.assertEqual(new_type_refcnt + 1, A.refcnt_in_del)
436
437 # Test that the original type already has decreased its refcnt
438 self.assertEqual(type_refcnt - 1, sys.getrefcount(B))
439
440 # Test that subtype_dealloc decref the newly assigned __class__ only once
441 self.assertEqual(new_type_refcnt, sys.getrefcount(A))
442
Eddie Elizondo3368f3c2019-09-19 09:29:05 -0700443 def test_heaptype_with_dict(self):
444 inst = _testcapi.HeapCTypeWithDict()
445 inst.foo = 42
446 self.assertEqual(inst.foo, 42)
447 self.assertEqual(inst.dictobj, inst.__dict__)
448 self.assertEqual(inst.dictobj, {"foo": 42})
449
450 inst = _testcapi.HeapCTypeWithDict()
451 self.assertEqual({}, inst.__dict__)
452
453 def test_heaptype_with_negative_dict(self):
454 inst = _testcapi.HeapCTypeWithNegativeDict()
455 inst.foo = 42
456 self.assertEqual(inst.foo, 42)
457 self.assertEqual(inst.dictobj, inst.__dict__)
458 self.assertEqual(inst.dictobj, {"foo": 42})
459
460 inst = _testcapi.HeapCTypeWithNegativeDict()
461 self.assertEqual({}, inst.__dict__)
462
463 def test_heaptype_with_weakref(self):
464 inst = _testcapi.HeapCTypeWithWeakref()
465 ref = weakref.ref(inst)
466 self.assertEqual(ref(), inst)
467 self.assertEqual(inst.weakreflist, ref)
468
Eddie Elizondoff023ed2019-09-11 05:17:13 -0400469 def test_c_subclass_of_heap_ctype_with_tpdealloc_decrefs_once(self):
470 subclass_instance = _testcapi.HeapCTypeSubclass()
471 type_refcnt = sys.getrefcount(_testcapi.HeapCTypeSubclass)
472
473 # Test that subclass instance was fully created
474 self.assertEqual(subclass_instance.value, 10)
475 self.assertEqual(subclass_instance.value2, 20)
476
477 # Test that the type reference count is only decremented once
478 del subclass_instance
479 self.assertEqual(type_refcnt - 1, sys.getrefcount(_testcapi.HeapCTypeSubclass))
480
481 def test_c_subclass_of_heap_ctype_with_del_modifying_dunder_class_only_decrefs_once(self):
482 subclass_instance = _testcapi.HeapCTypeSubclassWithFinalizer()
483 type_refcnt = sys.getrefcount(_testcapi.HeapCTypeSubclassWithFinalizer)
484 new_type_refcnt = sys.getrefcount(_testcapi.HeapCTypeSubclass)
485
486 # Test that subclass instance was fully created
487 self.assertEqual(subclass_instance.value, 10)
488 self.assertEqual(subclass_instance.value2, 20)
489
490 # The tp_finalize slot will set __class__ to HeapCTypeSubclass
491 del subclass_instance
492
493 # Test that setting __class__ modified the reference counts of the types
494 self.assertEqual(type_refcnt - 1, _testcapi.HeapCTypeSubclassWithFinalizer.refcnt_in_del)
495 self.assertEqual(new_type_refcnt + 1, _testcapi.HeapCTypeSubclass.refcnt_in_del)
496
497 # Test that the original type already has decreased its refcnt
498 self.assertEqual(type_refcnt - 1, sys.getrefcount(_testcapi.HeapCTypeSubclassWithFinalizer))
499
500 # Test that subtype_dealloc decref the newly assigned __class__ only once
501 self.assertEqual(new_type_refcnt, sys.getrefcount(_testcapi.HeapCTypeSubclass))
502
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800503
Benjamin Petersona54c9092009-01-13 02:11:23 +0000504class TestPendingCalls(unittest.TestCase):
505
506 def pendingcalls_submit(self, l, n):
507 def callback():
508 #this function can be interrupted by thread switching so let's
509 #use an atomic operation
510 l.append(None)
511
512 for i in range(n):
513 time.sleep(random.random()*0.02) #0.01 secs on average
514 #try submitting callback until successful.
515 #rely on regular interrupt to flush queue if we are
516 #unsuccessful.
517 while True:
518 if _testcapi._pending_threadfunc(callback):
519 break;
520
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000521 def pendingcalls_wait(self, l, n, context = None):
Benjamin Petersona54c9092009-01-13 02:11:23 +0000522 #now, stick around until l[0] has grown to 10
523 count = 0;
524 while len(l) != n:
525 #this busy loop is where we expect to be interrupted to
526 #run our callbacks. Note that callbacks are only run on the
527 #main thread
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000528 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +0000529 print("(%i)"%(len(l),),)
530 for i in range(1000):
531 a = i*i
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000532 if context and not context.event.is_set():
533 continue
Benjamin Petersona54c9092009-01-13 02:11:23 +0000534 count += 1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000535 self.assertTrue(count < 10000,
Benjamin Petersona54c9092009-01-13 02:11:23 +0000536 "timeout waiting for %i callbacks, got %i"%(n, len(l)))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000537 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +0000538 print("(%i)"%(len(l),))
539
540 def test_pendingcalls_threaded(self):
Benjamin Petersona54c9092009-01-13 02:11:23 +0000541
542 #do every callback on a separate thread
Victor Stinnere225beb2019-06-03 18:14:24 +0200543 n = 32 #total callbacks
Benjamin Petersona54c9092009-01-13 02:11:23 +0000544 threads = []
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000545 class foo(object):pass
546 context = foo()
547 context.l = []
548 context.n = 2 #submits per thread
549 context.nThreads = n // context.n
550 context.nFinished = 0
551 context.lock = threading.Lock()
552 context.event = threading.Event()
553
Serhiy Storchaka263dcd22015-04-01 13:01:14 +0300554 threads = [threading.Thread(target=self.pendingcalls_thread,
555 args=(context,))
556 for i in range(context.nThreads)]
557 with support.start_threads(threads):
558 self.pendingcalls_wait(context.l, n, context)
Benjamin Petersona54c9092009-01-13 02:11:23 +0000559
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000560 def pendingcalls_thread(self, context):
561 try:
562 self.pendingcalls_submit(context.l, context.n)
563 finally:
564 with context.lock:
565 context.nFinished += 1
566 nFinished = context.nFinished
567 if False and support.verbose:
568 print("finished threads: ", nFinished)
569 if nFinished == context.nThreads:
570 context.event.set()
571
Benjamin Petersona54c9092009-01-13 02:11:23 +0000572 def test_pendingcalls_non_threaded(self):
Ezio Melotti13925002011-03-16 11:05:33 +0200573 #again, just using the main thread, likely they will all be dispatched at
Benjamin Petersona54c9092009-01-13 02:11:23 +0000574 #once. It is ok to ask for too many, because we loop until we find a slot.
575 #the loop can be interrupted to dispatch.
576 #there are only 32 dispatch slots, so we go for twice that!
577 l = []
578 n = 64
579 self.pendingcalls_submit(l, n)
580 self.pendingcalls_wait(l, n)
581
Antoine Pitrou7a2572c2013-08-01 20:43:26 +0200582
583class SubinterpreterTest(unittest.TestCase):
584
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100585 def test_subinterps(self):
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100586 import builtins
587 r, w = os.pipe()
588 code = """if 1:
589 import sys, builtins, pickle
590 with open({:d}, "wb") as f:
591 pickle.dump(id(sys.modules), f)
592 pickle.dump(id(builtins), f)
593 """.format(w)
594 with open(r, "rb") as f:
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100595 ret = support.run_in_subinterp(code)
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100596 self.assertEqual(ret, 0)
597 self.assertNotEqual(pickle.load(f), id(sys.modules))
598 self.assertNotEqual(pickle.load(f), id(builtins))
599
Marcel Plch33e71e02019-05-22 13:51:26 +0200600 def test_mutate_exception(self):
601 """
602 Exceptions saved in global module state get shared between
603 individual module instances. This test checks whether or not
604 a change in one interpreter's module gets reflected into the
605 other ones.
606 """
607 import binascii
608
609 support.run_in_subinterp("import binascii; binascii.Error.foobar = 'foobar'")
610
611 self.assertFalse(hasattr(binascii.Error, "foobar"))
612
Antoine Pitrou7a2572c2013-08-01 20:43:26 +0200613
Ezio Melotti29267c82013-02-23 05:52:46 +0200614class TestThreadState(unittest.TestCase):
615
616 @support.reap_threads
617 def test_thread_state(self):
618 # some extra thread-state tests driven via _testcapi
619 def target():
620 idents = []
621
622 def callback():
Ezio Melotti35246bd2013-02-23 05:58:38 +0200623 idents.append(threading.get_ident())
Ezio Melotti29267c82013-02-23 05:52:46 +0200624
625 _testcapi._test_thread_state(callback)
626 a = b = callback
627 time.sleep(1)
628 # Check our main thread is in the list exactly 3 times.
Ezio Melotti35246bd2013-02-23 05:58:38 +0200629 self.assertEqual(idents.count(threading.get_ident()), 3,
Ezio Melotti29267c82013-02-23 05:52:46 +0200630 "Couldn't find main thread correctly in the list")
631
632 target()
633 t = threading.Thread(target=target)
634 t.start()
635 t.join()
636
Victor Stinner34be8072016-03-14 12:04:26 +0100637
Zachary Warec12f09e2013-11-11 22:47:04 -0600638class Test_testcapi(unittest.TestCase):
Serhiy Storchaka8f7bb102018-08-06 16:50:19 +0300639 locals().update((name, getattr(_testcapi, name))
640 for name in dir(_testcapi)
641 if name.startswith('test_') and not name.endswith('_code'))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000642
Victor Stinner34be8072016-03-14 12:04:26 +0100643
Victor Stinnerc4aec362016-03-14 22:26:53 +0100644class PyMemDebugTests(unittest.TestCase):
645 PYTHONMALLOC = 'debug'
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100646 # '0x04c06e0' or '04C06E0'
Victor Stinner08572f62016-03-14 21:55:43 +0100647 PTR_REGEX = r'(?:0x)?[0-9a-fA-F]+'
Victor Stinner34be8072016-03-14 12:04:26 +0100648
649 def check(self, code):
650 with support.SuppressCrashReport():
Victor Stinnerc4aec362016-03-14 22:26:53 +0100651 out = assert_python_failure('-c', code,
652 PYTHONMALLOC=self.PYTHONMALLOC)
Victor Stinner34be8072016-03-14 12:04:26 +0100653 stderr = out.err
654 return stderr.decode('ascii', 'replace')
655
656 def test_buffer_overflow(self):
657 out = self.check('import _testcapi; _testcapi.pymem_buffer_overflow()')
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100658 regex = (r"Debug memory block at address p={ptr}: API 'm'\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100659 r" 16 bytes originally requested\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100660 r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n"
661 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 +0100662 r" at tail\+0: 0x78 \*\*\* OUCH\n"
Victor Stinner4c409be2019-04-11 13:01:15 +0200663 r" at tail\+1: 0xfd\n"
664 r" at tail\+2: 0xfd\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100665 r" .*\n"
Victor Stinnere8f9acf2019-04-12 21:54:06 +0200666 r"( The block was made by call #[0-9]+ to debug malloc/realloc.\n)?"
Victor Stinner4c409be2019-04-11 13:01:15 +0200667 r" Data at p: cd cd cd .*\n"
Victor Stinner6453e9e2016-03-15 23:36:28 +0100668 r"\n"
Victor Stinnerf966e532018-11-13 15:14:58 +0100669 r"Enable tracemalloc to get the memory block allocation traceback\n"
670 r"\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100671 r"Fatal Python error: bad trailing pad byte")
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100672 regex = regex.format(ptr=self.PTR_REGEX)
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100673 regex = re.compile(regex, flags=re.DOTALL)
Victor Stinner34be8072016-03-14 12:04:26 +0100674 self.assertRegex(out, regex)
675
676 def test_api_misuse(self):
677 out = self.check('import _testcapi; _testcapi.pymem_api_misuse()')
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100678 regex = (r"Debug memory block at address p={ptr}: API 'm'\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100679 r" 16 bytes originally requested\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100680 r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n"
681 r" The [0-9] pad bytes at tail={ptr} are FORBIDDENBYTE, as expected.\n"
Victor Stinnere8f9acf2019-04-12 21:54:06 +0200682 r"( The block was made by call #[0-9]+ to debug malloc/realloc.\n)?"
Victor Stinner4c409be2019-04-11 13:01:15 +0200683 r" Data at p: cd cd cd .*\n"
Victor Stinner6453e9e2016-03-15 23:36:28 +0100684 r"\n"
Victor Stinnerf966e532018-11-13 15:14:58 +0100685 r"Enable tracemalloc to get the memory block allocation traceback\n"
686 r"\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100687 r"Fatal Python error: bad ID: Allocated using API 'm', verified using API 'r'\n")
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100688 regex = regex.format(ptr=self.PTR_REGEX)
Victor Stinner34be8072016-03-14 12:04:26 +0100689 self.assertRegex(out, regex)
690
Victor Stinnerad524372016-03-16 12:12:53 +0100691 def check_malloc_without_gil(self, code):
Victor Stinnerc4aec362016-03-14 22:26:53 +0100692 out = self.check(code)
693 expected = ('Fatal Python error: Python memory allocator called '
694 'without holding the GIL')
695 self.assertIn(expected, out)
Victor Stinner34be8072016-03-14 12:04:26 +0100696
Victor Stinnerad524372016-03-16 12:12:53 +0100697 def test_pymem_malloc_without_gil(self):
698 # Debug hooks must raise an error if PyMem_Malloc() is called
699 # without holding the GIL
700 code = 'import _testcapi; _testcapi.pymem_malloc_without_gil()'
701 self.check_malloc_without_gil(code)
702
703 def test_pyobject_malloc_without_gil(self):
704 # Debug hooks must raise an error if PyObject_Malloc() is called
705 # without holding the GIL
706 code = 'import _testcapi; _testcapi.pyobject_malloc_without_gil()'
707 self.check_malloc_without_gil(code)
708
Victor Stinner3bf0f3a2019-06-07 16:22:21 +0200709 def check_pyobject_is_freed(self, func_name):
710 code = textwrap.dedent(f'''
Victor Stinner2b00db62019-04-11 11:33:27 +0200711 import gc, os, sys, _testcapi
712 # Disable the GC to avoid crash on GC collection
713 gc.disable()
Victor Stinner3bf0f3a2019-06-07 16:22:21 +0200714 try:
715 _testcapi.{func_name}()
716 # Exit immediately to avoid a crash while deallocating
717 # the invalid object
718 os._exit(0)
719 except _testcapi.error:
720 os._exit(1)
Victor Stinner2b00db62019-04-11 11:33:27 +0200721 ''')
Victor Stinner2b00db62019-04-11 11:33:27 +0200722 assert_python_ok('-c', code, PYTHONMALLOC=self.PYTHONMALLOC)
723
Victor Stinner68762572019-10-07 18:42:01 +0200724 def test_pyobject_null_is_freed(self):
725 self.check_pyobject_is_freed('check_pyobject_null_is_freed')
726
Victor Stinner3bf0f3a2019-06-07 16:22:21 +0200727 def test_pyobject_uninitialized_is_freed(self):
728 self.check_pyobject_is_freed('check_pyobject_uninitialized_is_freed')
Victor Stinner2b00db62019-04-11 11:33:27 +0200729
Victor Stinner3bf0f3a2019-06-07 16:22:21 +0200730 def test_pyobject_forbidden_bytes_is_freed(self):
731 self.check_pyobject_is_freed('check_pyobject_forbidden_bytes_is_freed')
Victor Stinner2b00db62019-04-11 11:33:27 +0200732
Victor Stinner3bf0f3a2019-06-07 16:22:21 +0200733 def test_pyobject_freed_is_freed(self):
734 self.check_pyobject_is_freed('check_pyobject_freed_is_freed')
Victor Stinner2b00db62019-04-11 11:33:27 +0200735
Victor Stinnerc4aec362016-03-14 22:26:53 +0100736
737class PyMemMallocDebugTests(PyMemDebugTests):
738 PYTHONMALLOC = 'malloc_debug'
Victor Stinner34be8072016-03-14 12:04:26 +0100739
740
Victor Stinner5d39e042017-11-29 17:20:38 +0100741@unittest.skipUnless(support.with_pymalloc(), 'need pymalloc')
Victor Stinnerc4aec362016-03-14 22:26:53 +0100742class PyMemPymallocDebugTests(PyMemDebugTests):
743 PYTHONMALLOC = 'pymalloc_debug'
Victor Stinner34be8072016-03-14 12:04:26 +0100744
745
746@unittest.skipUnless(Py_DEBUG, 'need Py_DEBUG')
Victor Stinnerc4aec362016-03-14 22:26:53 +0100747class PyMemDefaultTests(PyMemDebugTests):
748 # test default allocator of Python compiled in debug mode
749 PYTHONMALLOC = ''
Victor Stinner34be8072016-03-14 12:04:26 +0100750
751
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000752if __name__ == "__main__":
Zachary Warec12f09e2013-11-11 22:47:04 -0600753 unittest.main()