blob: fa5ca1c97f458328d1b3eee21514d57035ca678e [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
Petr Viktorine1becf42020-05-07 15:39:59 +020016import importlib.machinery
17import importlib.util
Benjamin Petersonee8712c2008-05-20 21:35:26 +000018from test import support
Larry Hastingsfcafe432013-11-23 17:35:48 -080019from test.support import MISSING_C_DOCSTRINGS
Hai Shie80697d2020-05-28 06:10:27 +080020from test.support import threading_helper
xdegaye85f64302017-07-01 14:14:45 +020021from test.support.script_helper import assert_python_failure, assert_python_ok
Victor Stinner45df8202010-04-28 22:31:17 +000022try:
Stefan Krahfd24f9e2012-08-20 11:04:24 +020023 import _posixsubprocess
24except ImportError:
25 _posixsubprocess = None
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020026
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +020027# Skip this test if the _testcapi module isn't available.
28_testcapi = support.import_module('_testcapi')
Tim Peters9ea17ac2001-02-02 05:57:15 +000029
Victor Stinner1ae035b2020-04-17 17:47:20 +020030import _testinternalcapi
31
Victor Stinnerefde1462015-03-21 15:04:43 +010032# Were we compiled --with-pydebug or with #define Py_DEBUG?
33Py_DEBUG = hasattr(sys, 'gettotalrefcount')
34
Benjamin Petersona54c9092009-01-13 02:11:23 +000035
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000036def testfunction(self):
37 """some doc"""
38 return self
39
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +020040
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000041class InstanceMethod:
42 id = _testcapi.instancemethod(id)
43 testfunction = _testcapi.instancemethod(testfunction)
44
45class CAPITest(unittest.TestCase):
46
47 def test_instancemethod(self):
48 inst = InstanceMethod()
49 self.assertEqual(id(inst), inst.id())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000050 self.assertTrue(inst.testfunction() is inst)
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000051 self.assertEqual(inst.testfunction.__doc__, testfunction.__doc__)
52 self.assertEqual(InstanceMethod.testfunction.__doc__, testfunction.__doc__)
53
54 InstanceMethod.testfunction.attribute = "test"
55 self.assertEqual(testfunction.attribute, "test")
56 self.assertRaises(AttributeError, setattr, inst.testfunction, "attribute", "test")
57
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000058 def test_no_FatalError_infinite_loop(self):
Antoine Pitrou77e904e2013-10-08 23:04:32 +020059 with support.SuppressCrashReport():
Ezio Melotti25a40452013-03-05 20:26:17 +020060 p = subprocess.Popen([sys.executable, "-c",
Ezio Melottie1857d92013-03-05 20:31:34 +020061 'import _testcapi;'
62 '_testcapi.crash_no_current_thread()'],
63 stdout=subprocess.PIPE,
64 stderr=subprocess.PIPE)
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000065 (out, err) = p.communicate()
66 self.assertEqual(out, b'')
67 # This used to cause an infinite loop.
Vinay Sajip73954042012-05-06 11:34:50 +010068 self.assertTrue(err.rstrip().startswith(
Victor Stinner9e5d30c2020-03-07 00:54:20 +010069 b'Fatal Python error: '
Victor Stinner23ef89d2020-03-18 02:26:04 +010070 b'PyThreadState_Get: '
Victor Stinner3026cad2020-06-01 16:02:40 +020071 b'the function must be called with the GIL held, '
72 b'but the GIL is released '
73 b'(the current Python thread state is NULL)'),
74 err)
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000075
Antoine Pitrou915605c2011-02-24 20:53:48 +000076 def test_memoryview_from_NULL_pointer(self):
77 self.assertRaises(ValueError, _testcapi.make_memoryview_from_NULL_pointer)
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000078
Martin v. Löwisaa2efcb2012-04-19 14:33:43 +020079 def test_exc_info(self):
80 raised_exception = ValueError("5")
81 new_exc = TypeError("TEST")
82 try:
83 raise raised_exception
84 except ValueError as e:
85 tb = e.__traceback__
86 orig_sys_exc_info = sys.exc_info()
87 orig_exc_info = _testcapi.set_exc_info(new_exc.__class__, new_exc, None)
88 new_sys_exc_info = sys.exc_info()
89 new_exc_info = _testcapi.set_exc_info(*orig_exc_info)
90 reset_sys_exc_info = sys.exc_info()
91
92 self.assertEqual(orig_exc_info[1], e)
93
94 self.assertSequenceEqual(orig_exc_info, (raised_exception.__class__, raised_exception, tb))
95 self.assertSequenceEqual(orig_sys_exc_info, orig_exc_info)
96 self.assertSequenceEqual(reset_sys_exc_info, orig_exc_info)
97 self.assertSequenceEqual(new_exc_info, (new_exc.__class__, new_exc, None))
98 self.assertSequenceEqual(new_sys_exc_info, new_exc_info)
99 else:
100 self.assertTrue(False)
101
Stefan Krahfd24f9e2012-08-20 11:04:24 +0200102 @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
103 def test_seq_bytes_to_charp_array(self):
104 # Issue #15732: crash in _PySequence_BytesToCharpArray()
105 class Z(object):
106 def __len__(self):
107 return 1
108 self.assertRaises(TypeError, _posixsubprocess.fork_exec,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -0700109 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 +0200110 # Issue #15736: overflow in _PySequence_BytesToCharpArray()
111 class Z(object):
112 def __len__(self):
113 return sys.maxsize
114 def __getitem__(self, i):
115 return b'x'
116 self.assertRaises(MemoryError, _posixsubprocess.fork_exec,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -0700117 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 +0200118
Stefan Krahdb579d72012-08-20 14:36:47 +0200119 @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
120 def test_subprocess_fork_exec(self):
121 class Z(object):
122 def __len__(self):
123 return 1
124
125 # Issue #15738: crash in subprocess_fork_exec()
126 self.assertRaises(TypeError, _posixsubprocess.fork_exec,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -0700127 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 +0200128
Larry Hastingsfcafe432013-11-23 17:35:48 -0800129 @unittest.skipIf(MISSING_C_DOCSTRINGS,
130 "Signature information for builtins requires docstrings")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800131 def test_docstring_signature_parsing(self):
132
133 self.assertEqual(_testcapi.no_docstring.__doc__, None)
134 self.assertEqual(_testcapi.no_docstring.__text_signature__, None)
135
Zachary Ware8ef887c2015-04-13 18:22:35 -0500136 self.assertEqual(_testcapi.docstring_empty.__doc__, None)
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800137 self.assertEqual(_testcapi.docstring_empty.__text_signature__, None)
138
139 self.assertEqual(_testcapi.docstring_no_signature.__doc__,
140 "This docstring has no signature.")
141 self.assertEqual(_testcapi.docstring_no_signature.__text_signature__, None)
142
143 self.assertEqual(_testcapi.docstring_with_invalid_signature.__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800144 "docstring_with_invalid_signature($module, /, boo)\n"
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800145 "\n"
146 "This docstring has an invalid signature."
147 )
148 self.assertEqual(_testcapi.docstring_with_invalid_signature.__text_signature__, None)
149
Larry Hastings2623c8c2014-02-08 22:15:29 -0800150 self.assertEqual(_testcapi.docstring_with_invalid_signature2.__doc__,
151 "docstring_with_invalid_signature2($module, /, boo)\n"
152 "\n"
153 "--\n"
154 "\n"
155 "This docstring also has an invalid signature."
156 )
157 self.assertEqual(_testcapi.docstring_with_invalid_signature2.__text_signature__, None)
158
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800159 self.assertEqual(_testcapi.docstring_with_signature.__doc__,
160 "This docstring has a valid signature.")
Larry Hastings2623c8c2014-02-08 22:15:29 -0800161 self.assertEqual(_testcapi.docstring_with_signature.__text_signature__, "($module, /, sig)")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800162
Zachary Ware8ef887c2015-04-13 18:22:35 -0500163 self.assertEqual(_testcapi.docstring_with_signature_but_no_doc.__doc__, None)
164 self.assertEqual(_testcapi.docstring_with_signature_but_no_doc.__text_signature__,
165 "($module, /, sig)")
166
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800167 self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800168 "\nThis docstring has a valid signature and some extra newlines.")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800169 self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__text_signature__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800170 "($module, /, parameter)")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800171
Benjamin Petersond51374e2014-04-09 23:55:56 -0400172 def test_c_type_with_matrix_multiplication(self):
173 M = _testcapi.matmulType
174 m1 = M()
175 m2 = M()
176 self.assertEqual(m1 @ m2, ("matmul", m1, m2))
177 self.assertEqual(m1 @ 42, ("matmul", m1, 42))
178 self.assertEqual(42 @ m1, ("matmul", 42, m1))
179 o = m1
180 o @= m2
181 self.assertEqual(o, ("imatmul", m1, m2))
182 o = m1
183 o @= 42
184 self.assertEqual(o, ("imatmul", m1, 42))
185 o = 42
186 o @= m1
187 self.assertEqual(o, ("matmul", 42, m1))
188
Zackery Spytzc7f803b2019-05-31 03:46:36 -0600189 def test_c_type_with_ipow(self):
190 # When the __ipow__ method of a type was implemented in C, using the
191 # modulo param would cause segfaults.
192 o = _testcapi.ipowType()
193 self.assertEqual(o.__ipow__(1), (1, None))
194 self.assertEqual(o.__ipow__(2, 2), (2, 2))
195
Victor Stinnerefde1462015-03-21 15:04:43 +0100196 def test_return_null_without_error(self):
197 # Issue #23571: A function must not return NULL without setting an
198 # error
199 if Py_DEBUG:
200 code = textwrap.dedent("""
201 import _testcapi
202 from test import support
203
204 with support.SuppressCrashReport():
205 _testcapi.return_null_without_error()
206 """)
207 rc, out, err = assert_python_failure('-c', code)
Victor Stinner381a9bc2015-03-24 14:01:32 +0100208 self.assertRegex(err.replace(b'\r', b''),
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100209 br'Fatal Python error: _Py_CheckFunctionResult: '
210 br'a function returned NULL '
Victor Stinner944fbcc2015-03-24 16:28:52 +0100211 br'without setting an error\n'
Victor Stinner1ce16fb2019-09-18 01:35:33 +0200212 br'Python runtime state: initialized\n'
Victor Stinner381a9bc2015-03-24 14:01:32 +0100213 br'SystemError: <built-in function '
214 br'return_null_without_error> returned NULL '
215 br'without setting an error\n'
216 br'\n'
217 br'Current thread.*:\n'
218 br' File .*", line 6 in <module>')
Victor Stinnerefde1462015-03-21 15:04:43 +0100219 else:
220 with self.assertRaises(SystemError) as cm:
221 _testcapi.return_null_without_error()
222 self.assertRegex(str(cm.exception),
223 'return_null_without_error.* '
224 'returned NULL without setting an error')
225
226 def test_return_result_with_error(self):
227 # Issue #23571: A function must not return a result with an error set
228 if Py_DEBUG:
229 code = textwrap.dedent("""
230 import _testcapi
231 from test import support
232
233 with support.SuppressCrashReport():
234 _testcapi.return_result_with_error()
235 """)
236 rc, out, err = assert_python_failure('-c', code)
Victor Stinner381a9bc2015-03-24 14:01:32 +0100237 self.assertRegex(err.replace(b'\r', b''),
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100238 br'Fatal Python error: _Py_CheckFunctionResult: '
239 br'a function returned a result '
240 br'with an error set\n'
Victor Stinner1ce16fb2019-09-18 01:35:33 +0200241 br'Python runtime state: initialized\n'
Victor Stinner381a9bc2015-03-24 14:01:32 +0100242 br'ValueError\n'
243 br'\n'
Serhiy Storchaka467ab192016-10-21 17:09:17 +0300244 br'The above exception was the direct cause '
245 br'of the following exception:\n'
Victor Stinner381a9bc2015-03-24 14:01:32 +0100246 br'\n'
247 br'SystemError: <built-in '
248 br'function return_result_with_error> '
249 br'returned a result with an error set\n'
250 br'\n'
251 br'Current thread.*:\n'
252 br' File .*, line 6 in <module>')
Victor Stinnerefde1462015-03-21 15:04:43 +0100253 else:
254 with self.assertRaises(SystemError) as cm:
255 _testcapi.return_result_with_error()
256 self.assertRegex(str(cm.exception),
257 'return_result_with_error.* '
258 'returned a result with an error set')
259
Serhiy Storchaka13e602e2016-05-20 22:31:14 +0300260 def test_buildvalue_N(self):
261 _testcapi.test_buildvalue_N()
262
xdegaye85f64302017-07-01 14:14:45 +0200263 def test_set_nomemory(self):
264 code = """if 1:
265 import _testcapi
266
267 class C(): pass
268
269 # The first loop tests both functions and that remove_mem_hooks()
270 # can be called twice in a row. The second loop checks a call to
271 # set_nomemory() after a call to remove_mem_hooks(). The third
272 # loop checks the start and stop arguments of set_nomemory().
273 for outer_cnt in range(1, 4):
274 start = 10 * outer_cnt
275 for j in range(100):
276 if j == 0:
277 if outer_cnt != 3:
278 _testcapi.set_nomemory(start)
279 else:
280 _testcapi.set_nomemory(start, start + 1)
281 try:
282 C()
283 except MemoryError as e:
284 if outer_cnt != 3:
285 _testcapi.remove_mem_hooks()
286 print('MemoryError', outer_cnt, j)
287 _testcapi.remove_mem_hooks()
288 break
289 """
290 rc, out, err = assert_python_ok('-c', code)
291 self.assertIn(b'MemoryError 1 10', out)
292 self.assertIn(b'MemoryError 2 20', out)
293 self.assertIn(b'MemoryError 3 30', out)
294
Oren Milman0ccc0f62017-10-08 11:17:46 +0300295 def test_mapping_keys_values_items(self):
296 class Mapping1(dict):
297 def keys(self):
298 return list(super().keys())
299 def values(self):
300 return list(super().values())
301 def items(self):
302 return list(super().items())
303 class Mapping2(dict):
304 def keys(self):
305 return tuple(super().keys())
306 def values(self):
307 return tuple(super().values())
308 def items(self):
309 return tuple(super().items())
310 dict_obj = {'foo': 1, 'bar': 2, 'spam': 3}
311
312 for mapping in [{}, OrderedDict(), Mapping1(), Mapping2(),
313 dict_obj, OrderedDict(dict_obj),
314 Mapping1(dict_obj), Mapping2(dict_obj)]:
315 self.assertListEqual(_testcapi.get_mapping_keys(mapping),
316 list(mapping.keys()))
317 self.assertListEqual(_testcapi.get_mapping_values(mapping),
318 list(mapping.values()))
319 self.assertListEqual(_testcapi.get_mapping_items(mapping),
320 list(mapping.items()))
321
322 def test_mapping_keys_values_items_bad_arg(self):
323 self.assertRaises(AttributeError, _testcapi.get_mapping_keys, None)
324 self.assertRaises(AttributeError, _testcapi.get_mapping_values, None)
325 self.assertRaises(AttributeError, _testcapi.get_mapping_items, None)
326
327 class BadMapping:
328 def keys(self):
329 return None
330 def values(self):
331 return None
332 def items(self):
333 return None
334 bad_mapping = BadMapping()
335 self.assertRaises(TypeError, _testcapi.get_mapping_keys, bad_mapping)
336 self.assertRaises(TypeError, _testcapi.get_mapping_values, bad_mapping)
337 self.assertRaises(TypeError, _testcapi.get_mapping_items, bad_mapping)
338
Victor Stinner18618e652018-10-25 17:28:11 +0200339 @unittest.skipUnless(hasattr(_testcapi, 'negative_refcount'),
340 'need _testcapi.negative_refcount')
341 def test_negative_refcount(self):
342 # bpo-35059: Check that Py_DECREF() reports the correct filename
343 # when calling _Py_NegativeRefcount() to abort Python.
344 code = textwrap.dedent("""
345 import _testcapi
346 from test import support
347
348 with support.SuppressCrashReport():
349 _testcapi.negative_refcount()
350 """)
351 rc, out, err = assert_python_failure('-c', code)
352 self.assertRegex(err,
Victor Stinner3ec9af72018-10-26 02:12:34 +0200353 br'_testcapimodule\.c:[0-9]+: '
Victor Stinnerf1d002c2018-11-21 23:53:44 +0100354 br'_Py_NegativeRefcount: Assertion failed: '
Victor Stinner3ec9af72018-10-26 02:12:34 +0200355 br'object has negative ref count')
Victor Stinner18618e652018-10-25 17:28:11 +0200356
Jeroen Demeyer351c6742019-05-10 19:21:11 +0200357 def test_trashcan_subclass(self):
358 # bpo-35983: Check that the trashcan mechanism for "list" is NOT
359 # activated when its tp_dealloc is being called by a subclass
360 from _testcapi import MyList
361 L = None
362 for i in range(1000):
363 L = MyList((L,))
364
Victor Stinner0127bb12019-11-21 12:54:02 +0100365 @support.requires_resource('cpu')
Jeroen Demeyer351c6742019-05-10 19:21:11 +0200366 def test_trashcan_python_class1(self):
367 self.do_test_trashcan_python_class(list)
368
Victor Stinner0127bb12019-11-21 12:54:02 +0100369 @support.requires_resource('cpu')
Jeroen Demeyer351c6742019-05-10 19:21:11 +0200370 def test_trashcan_python_class2(self):
371 from _testcapi import MyList
372 self.do_test_trashcan_python_class(MyList)
373
374 def do_test_trashcan_python_class(self, base):
375 # Check that the trashcan mechanism works properly for a Python
376 # subclass of a class using the trashcan (this specific test assumes
377 # that the base class "base" behaves like list)
378 class PyList(base):
379 # Count the number of PyList instances to verify that there is
380 # no memory leak
381 num = 0
382 def __init__(self, *args):
383 __class__.num += 1
384 super().__init__(*args)
385 def __del__(self):
386 __class__.num -= 1
387
388 for parity in (0, 1):
389 L = None
390 # We need in the order of 2**20 iterations here such that a
391 # typical 8MB stack would overflow without the trashcan.
392 for i in range(2**20):
393 L = PyList((L,))
394 L.attr = i
395 if parity:
396 # Add one additional nesting layer
397 L = (L,)
398 self.assertGreater(PyList.num, 0)
399 del L
400 self.assertEqual(PyList.num, 0)
401
Eddie Elizondoff023ed2019-09-11 05:17:13 -0400402 def test_subclass_of_heap_gc_ctype_with_tpdealloc_decrefs_once(self):
403 class HeapGcCTypeSubclass(_testcapi.HeapGcCType):
404 def __init__(self):
405 self.value2 = 20
406 super().__init__()
407
408 subclass_instance = HeapGcCTypeSubclass()
409 type_refcnt = sys.getrefcount(HeapGcCTypeSubclass)
410
411 # Test that subclass instance was fully created
412 self.assertEqual(subclass_instance.value, 10)
413 self.assertEqual(subclass_instance.value2, 20)
414
415 # Test that the type reference count is only decremented once
416 del subclass_instance
417 self.assertEqual(type_refcnt - 1, sys.getrefcount(HeapGcCTypeSubclass))
418
419 def test_subclass_of_heap_gc_ctype_with_del_modifying_dunder_class_only_decrefs_once(self):
420 class A(_testcapi.HeapGcCType):
421 def __init__(self):
422 self.value2 = 20
423 super().__init__()
424
425 class B(A):
426 def __init__(self):
427 super().__init__()
428
429 def __del__(self):
430 self.__class__ = A
431 A.refcnt_in_del = sys.getrefcount(A)
432 B.refcnt_in_del = sys.getrefcount(B)
433
434 subclass_instance = B()
435 type_refcnt = sys.getrefcount(B)
436 new_type_refcnt = sys.getrefcount(A)
437
438 # Test that subclass instance was fully created
439 self.assertEqual(subclass_instance.value, 10)
440 self.assertEqual(subclass_instance.value2, 20)
441
442 del subclass_instance
443
444 # Test that setting __class__ modified the reference counts of the types
445 self.assertEqual(type_refcnt - 1, B.refcnt_in_del)
446 self.assertEqual(new_type_refcnt + 1, A.refcnt_in_del)
447
448 # Test that the original type already has decreased its refcnt
449 self.assertEqual(type_refcnt - 1, sys.getrefcount(B))
450
451 # Test that subtype_dealloc decref the newly assigned __class__ only once
452 self.assertEqual(new_type_refcnt, sys.getrefcount(A))
453
Eddie Elizondo3368f3c2019-09-19 09:29:05 -0700454 def test_heaptype_with_dict(self):
455 inst = _testcapi.HeapCTypeWithDict()
456 inst.foo = 42
457 self.assertEqual(inst.foo, 42)
458 self.assertEqual(inst.dictobj, inst.__dict__)
459 self.assertEqual(inst.dictobj, {"foo": 42})
460
461 inst = _testcapi.HeapCTypeWithDict()
462 self.assertEqual({}, inst.__dict__)
463
464 def test_heaptype_with_negative_dict(self):
465 inst = _testcapi.HeapCTypeWithNegativeDict()
466 inst.foo = 42
467 self.assertEqual(inst.foo, 42)
468 self.assertEqual(inst.dictobj, inst.__dict__)
469 self.assertEqual(inst.dictobj, {"foo": 42})
470
471 inst = _testcapi.HeapCTypeWithNegativeDict()
472 self.assertEqual({}, inst.__dict__)
473
474 def test_heaptype_with_weakref(self):
475 inst = _testcapi.HeapCTypeWithWeakref()
476 ref = weakref.ref(inst)
477 self.assertEqual(ref(), inst)
478 self.assertEqual(inst.weakreflist, ref)
479
scoderf7c4e232020-06-06 21:35:10 +0200480 def test_heaptype_with_buffer(self):
481 inst = _testcapi.HeapCTypeWithBuffer()
482 b = bytes(inst)
483 self.assertEqual(b, b"1234")
484
Eddie Elizondoff023ed2019-09-11 05:17:13 -0400485 def test_c_subclass_of_heap_ctype_with_tpdealloc_decrefs_once(self):
486 subclass_instance = _testcapi.HeapCTypeSubclass()
487 type_refcnt = sys.getrefcount(_testcapi.HeapCTypeSubclass)
488
489 # Test that subclass instance was fully created
490 self.assertEqual(subclass_instance.value, 10)
491 self.assertEqual(subclass_instance.value2, 20)
492
493 # Test that the type reference count is only decremented once
494 del subclass_instance
495 self.assertEqual(type_refcnt - 1, sys.getrefcount(_testcapi.HeapCTypeSubclass))
496
497 def test_c_subclass_of_heap_ctype_with_del_modifying_dunder_class_only_decrefs_once(self):
498 subclass_instance = _testcapi.HeapCTypeSubclassWithFinalizer()
499 type_refcnt = sys.getrefcount(_testcapi.HeapCTypeSubclassWithFinalizer)
500 new_type_refcnt = sys.getrefcount(_testcapi.HeapCTypeSubclass)
501
502 # Test that subclass instance was fully created
503 self.assertEqual(subclass_instance.value, 10)
504 self.assertEqual(subclass_instance.value2, 20)
505
506 # The tp_finalize slot will set __class__ to HeapCTypeSubclass
507 del subclass_instance
508
509 # Test that setting __class__ modified the reference counts of the types
510 self.assertEqual(type_refcnt - 1, _testcapi.HeapCTypeSubclassWithFinalizer.refcnt_in_del)
511 self.assertEqual(new_type_refcnt + 1, _testcapi.HeapCTypeSubclass.refcnt_in_del)
512
513 # Test that the original type already has decreased its refcnt
514 self.assertEqual(type_refcnt - 1, sys.getrefcount(_testcapi.HeapCTypeSubclassWithFinalizer))
515
516 # Test that subtype_dealloc decref the newly assigned __class__ only once
517 self.assertEqual(new_type_refcnt, sys.getrefcount(_testcapi.HeapCTypeSubclass))
518
Serhiy Storchakae5ccc942020-03-09 20:03:38 +0200519 def test_pynumber_tobase(self):
520 from _testcapi import pynumber_tobase
521 self.assertEqual(pynumber_tobase(123, 2), '0b1111011')
522 self.assertEqual(pynumber_tobase(123, 8), '0o173')
523 self.assertEqual(pynumber_tobase(123, 10), '123')
524 self.assertEqual(pynumber_tobase(123, 16), '0x7b')
525 self.assertEqual(pynumber_tobase(-123, 2), '-0b1111011')
526 self.assertEqual(pynumber_tobase(-123, 8), '-0o173')
527 self.assertEqual(pynumber_tobase(-123, 10), '-123')
528 self.assertEqual(pynumber_tobase(-123, 16), '-0x7b')
529 self.assertRaises(TypeError, pynumber_tobase, 123.0, 10)
530 self.assertRaises(TypeError, pynumber_tobase, '123', 10)
531 self.assertRaises(SystemError, pynumber_tobase, 123, 0)
532
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800533
Benjamin Petersona54c9092009-01-13 02:11:23 +0000534class TestPendingCalls(unittest.TestCase):
535
536 def pendingcalls_submit(self, l, n):
537 def callback():
538 #this function can be interrupted by thread switching so let's
539 #use an atomic operation
540 l.append(None)
541
542 for i in range(n):
543 time.sleep(random.random()*0.02) #0.01 secs on average
544 #try submitting callback until successful.
545 #rely on regular interrupt to flush queue if we are
546 #unsuccessful.
547 while True:
548 if _testcapi._pending_threadfunc(callback):
549 break;
550
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000551 def pendingcalls_wait(self, l, n, context = None):
Benjamin Petersona54c9092009-01-13 02:11:23 +0000552 #now, stick around until l[0] has grown to 10
553 count = 0;
554 while len(l) != n:
555 #this busy loop is where we expect to be interrupted to
556 #run our callbacks. Note that callbacks are only run on the
557 #main thread
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000558 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +0000559 print("(%i)"%(len(l),),)
560 for i in range(1000):
561 a = i*i
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000562 if context and not context.event.is_set():
563 continue
Benjamin Petersona54c9092009-01-13 02:11:23 +0000564 count += 1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000565 self.assertTrue(count < 10000,
Benjamin Petersona54c9092009-01-13 02:11:23 +0000566 "timeout waiting for %i callbacks, got %i"%(n, len(l)))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000567 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +0000568 print("(%i)"%(len(l),))
569
570 def test_pendingcalls_threaded(self):
Benjamin Petersona54c9092009-01-13 02:11:23 +0000571
572 #do every callback on a separate thread
Victor Stinnere225beb2019-06-03 18:14:24 +0200573 n = 32 #total callbacks
Benjamin Petersona54c9092009-01-13 02:11:23 +0000574 threads = []
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000575 class foo(object):pass
576 context = foo()
577 context.l = []
578 context.n = 2 #submits per thread
579 context.nThreads = n // context.n
580 context.nFinished = 0
581 context.lock = threading.Lock()
582 context.event = threading.Event()
583
Serhiy Storchaka263dcd22015-04-01 13:01:14 +0300584 threads = [threading.Thread(target=self.pendingcalls_thread,
585 args=(context,))
586 for i in range(context.nThreads)]
Hai Shie80697d2020-05-28 06:10:27 +0800587 with threading_helper.start_threads(threads):
Serhiy Storchaka263dcd22015-04-01 13:01:14 +0300588 self.pendingcalls_wait(context.l, n, context)
Benjamin Petersona54c9092009-01-13 02:11:23 +0000589
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000590 def pendingcalls_thread(self, context):
591 try:
592 self.pendingcalls_submit(context.l, context.n)
593 finally:
594 with context.lock:
595 context.nFinished += 1
596 nFinished = context.nFinished
597 if False and support.verbose:
598 print("finished threads: ", nFinished)
599 if nFinished == context.nThreads:
600 context.event.set()
601
Benjamin Petersona54c9092009-01-13 02:11:23 +0000602 def test_pendingcalls_non_threaded(self):
Ezio Melotti13925002011-03-16 11:05:33 +0200603 #again, just using the main thread, likely they will all be dispatched at
Benjamin Petersona54c9092009-01-13 02:11:23 +0000604 #once. It is ok to ask for too many, because we loop until we find a slot.
605 #the loop can be interrupted to dispatch.
606 #there are only 32 dispatch slots, so we go for twice that!
607 l = []
608 n = 64
609 self.pendingcalls_submit(l, n)
610 self.pendingcalls_wait(l, n)
611
Antoine Pitrou7a2572c2013-08-01 20:43:26 +0200612
613class SubinterpreterTest(unittest.TestCase):
614
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100615 def test_subinterps(self):
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100616 import builtins
617 r, w = os.pipe()
618 code = """if 1:
619 import sys, builtins, pickle
620 with open({:d}, "wb") as f:
621 pickle.dump(id(sys.modules), f)
622 pickle.dump(id(builtins), f)
623 """.format(w)
624 with open(r, "rb") as f:
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100625 ret = support.run_in_subinterp(code)
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100626 self.assertEqual(ret, 0)
627 self.assertNotEqual(pickle.load(f), id(sys.modules))
628 self.assertNotEqual(pickle.load(f), id(builtins))
629
Guido van Rossum9d197c72020-06-27 17:33:49 -0700630 def test_subinterps_recent_language_features(self):
631 r, w = os.pipe()
632 code = """if 1:
633 import pickle
634 with open({:d}, "wb") as f:
635
636 @(lambda x:x) # Py 3.9
637 def noop(x): return x
638
639 a = (b := f'1{{2}}3') + noop('x') # Py 3.8 (:=) / 3.6 (f'')
640
641 async def foo(arg): return await arg # Py 3.5
642
643 pickle.dump(dict(a=a, b=b), f)
644 """.format(w)
645
646 with open(r, "rb") as f:
647 ret = support.run_in_subinterp(code)
648 self.assertEqual(ret, 0)
649 self.assertEqual(pickle.load(f), {'a': '123x', 'b': '123'})
650
Marcel Plch33e71e02019-05-22 13:51:26 +0200651 def test_mutate_exception(self):
652 """
653 Exceptions saved in global module state get shared between
654 individual module instances. This test checks whether or not
655 a change in one interpreter's module gets reflected into the
656 other ones.
657 """
658 import binascii
659
660 support.run_in_subinterp("import binascii; binascii.Error.foobar = 'foobar'")
661
662 self.assertFalse(hasattr(binascii.Error, "foobar"))
663
Antoine Pitrou7a2572c2013-08-01 20:43:26 +0200664
Ezio Melotti29267c82013-02-23 05:52:46 +0200665class TestThreadState(unittest.TestCase):
666
Hai Shie80697d2020-05-28 06:10:27 +0800667 @threading_helper.reap_threads
Ezio Melotti29267c82013-02-23 05:52:46 +0200668 def test_thread_state(self):
669 # some extra thread-state tests driven via _testcapi
670 def target():
671 idents = []
672
673 def callback():
Ezio Melotti35246bd2013-02-23 05:58:38 +0200674 idents.append(threading.get_ident())
Ezio Melotti29267c82013-02-23 05:52:46 +0200675
676 _testcapi._test_thread_state(callback)
677 a = b = callback
678 time.sleep(1)
679 # Check our main thread is in the list exactly 3 times.
Ezio Melotti35246bd2013-02-23 05:58:38 +0200680 self.assertEqual(idents.count(threading.get_ident()), 3,
Ezio Melotti29267c82013-02-23 05:52:46 +0200681 "Couldn't find main thread correctly in the list")
682
683 target()
684 t = threading.Thread(target=target)
685 t.start()
686 t.join()
687
Victor Stinner34be8072016-03-14 12:04:26 +0100688
Zachary Warec12f09e2013-11-11 22:47:04 -0600689class Test_testcapi(unittest.TestCase):
Serhiy Storchaka8f7bb102018-08-06 16:50:19 +0300690 locals().update((name, getattr(_testcapi, name))
691 for name in dir(_testcapi)
692 if name.startswith('test_') and not name.endswith('_code'))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000693
Victor Stinner34be8072016-03-14 12:04:26 +0100694
Victor Stinner1ae035b2020-04-17 17:47:20 +0200695class Test_testinternalcapi(unittest.TestCase):
696 locals().update((name, getattr(_testinternalcapi, name))
697 for name in dir(_testinternalcapi)
698 if name.startswith('test_'))
699
700
Victor Stinnerc4aec362016-03-14 22:26:53 +0100701class PyMemDebugTests(unittest.TestCase):
702 PYTHONMALLOC = 'debug'
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100703 # '0x04c06e0' or '04C06E0'
Victor Stinner08572f62016-03-14 21:55:43 +0100704 PTR_REGEX = r'(?:0x)?[0-9a-fA-F]+'
Victor Stinner34be8072016-03-14 12:04:26 +0100705
706 def check(self, code):
707 with support.SuppressCrashReport():
Victor Stinnerc4aec362016-03-14 22:26:53 +0100708 out = assert_python_failure('-c', code,
709 PYTHONMALLOC=self.PYTHONMALLOC)
Victor Stinner34be8072016-03-14 12:04:26 +0100710 stderr = out.err
711 return stderr.decode('ascii', 'replace')
712
713 def test_buffer_overflow(self):
714 out = self.check('import _testcapi; _testcapi.pymem_buffer_overflow()')
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100715 regex = (r"Debug memory block at address p={ptr}: API 'm'\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100716 r" 16 bytes originally requested\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100717 r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n"
718 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 +0100719 r" at tail\+0: 0x78 \*\*\* OUCH\n"
Victor Stinner4c409be2019-04-11 13:01:15 +0200720 r" at tail\+1: 0xfd\n"
721 r" at tail\+2: 0xfd\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100722 r" .*\n"
Victor Stinnere8f9acf2019-04-12 21:54:06 +0200723 r"( The block was made by call #[0-9]+ to debug malloc/realloc.\n)?"
Victor Stinner4c409be2019-04-11 13:01:15 +0200724 r" Data at p: cd cd cd .*\n"
Victor Stinner6453e9e2016-03-15 23:36:28 +0100725 r"\n"
Victor Stinnerf966e532018-11-13 15:14:58 +0100726 r"Enable tracemalloc to get the memory block allocation traceback\n"
727 r"\n"
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100728 r"Fatal Python error: _PyMem_DebugRawFree: bad trailing pad byte")
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100729 regex = regex.format(ptr=self.PTR_REGEX)
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100730 regex = re.compile(regex, flags=re.DOTALL)
Victor Stinner34be8072016-03-14 12:04:26 +0100731 self.assertRegex(out, regex)
732
733 def test_api_misuse(self):
734 out = self.check('import _testcapi; _testcapi.pymem_api_misuse()')
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100735 regex = (r"Debug memory block at address p={ptr}: API 'm'\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100736 r" 16 bytes originally requested\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100737 r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n"
738 r" The [0-9] pad bytes at tail={ptr} are FORBIDDENBYTE, as expected.\n"
Victor Stinnere8f9acf2019-04-12 21:54:06 +0200739 r"( The block was made by call #[0-9]+ to debug malloc/realloc.\n)?"
Victor Stinner4c409be2019-04-11 13:01:15 +0200740 r" Data at p: cd cd cd .*\n"
Victor Stinner6453e9e2016-03-15 23:36:28 +0100741 r"\n"
Victor Stinnerf966e532018-11-13 15:14:58 +0100742 r"Enable tracemalloc to get the memory block allocation traceback\n"
743 r"\n"
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100744 r"Fatal Python error: _PyMem_DebugRawFree: bad ID: Allocated using API 'm', verified using API 'r'\n")
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100745 regex = regex.format(ptr=self.PTR_REGEX)
Victor Stinner34be8072016-03-14 12:04:26 +0100746 self.assertRegex(out, regex)
747
Victor Stinnerad524372016-03-16 12:12:53 +0100748 def check_malloc_without_gil(self, code):
Victor Stinnerc4aec362016-03-14 22:26:53 +0100749 out = self.check(code)
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100750 expected = ('Fatal Python error: _PyMem_DebugMalloc: '
751 'Python memory allocator called without holding the GIL')
Victor Stinnerc4aec362016-03-14 22:26:53 +0100752 self.assertIn(expected, out)
Victor Stinner34be8072016-03-14 12:04:26 +0100753
Victor Stinnerad524372016-03-16 12:12:53 +0100754 def test_pymem_malloc_without_gil(self):
755 # Debug hooks must raise an error if PyMem_Malloc() is called
756 # without holding the GIL
757 code = 'import _testcapi; _testcapi.pymem_malloc_without_gil()'
758 self.check_malloc_without_gil(code)
759
760 def test_pyobject_malloc_without_gil(self):
761 # Debug hooks must raise an error if PyObject_Malloc() is called
762 # without holding the GIL
763 code = 'import _testcapi; _testcapi.pyobject_malloc_without_gil()'
764 self.check_malloc_without_gil(code)
765
Victor Stinner3bf0f3a2019-06-07 16:22:21 +0200766 def check_pyobject_is_freed(self, func_name):
767 code = textwrap.dedent(f'''
Victor Stinner2b00db62019-04-11 11:33:27 +0200768 import gc, os, sys, _testcapi
769 # Disable the GC to avoid crash on GC collection
770 gc.disable()
Victor Stinner3bf0f3a2019-06-07 16:22:21 +0200771 try:
772 _testcapi.{func_name}()
773 # Exit immediately to avoid a crash while deallocating
774 # the invalid object
775 os._exit(0)
776 except _testcapi.error:
777 os._exit(1)
Victor Stinner2b00db62019-04-11 11:33:27 +0200778 ''')
Victor Stinner2b00db62019-04-11 11:33:27 +0200779 assert_python_ok('-c', code, PYTHONMALLOC=self.PYTHONMALLOC)
780
Victor Stinner68762572019-10-07 18:42:01 +0200781 def test_pyobject_null_is_freed(self):
782 self.check_pyobject_is_freed('check_pyobject_null_is_freed')
783
Victor Stinner3bf0f3a2019-06-07 16:22:21 +0200784 def test_pyobject_uninitialized_is_freed(self):
785 self.check_pyobject_is_freed('check_pyobject_uninitialized_is_freed')
Victor Stinner2b00db62019-04-11 11:33:27 +0200786
Victor Stinner3bf0f3a2019-06-07 16:22:21 +0200787 def test_pyobject_forbidden_bytes_is_freed(self):
788 self.check_pyobject_is_freed('check_pyobject_forbidden_bytes_is_freed')
Victor Stinner2b00db62019-04-11 11:33:27 +0200789
Victor Stinner3bf0f3a2019-06-07 16:22:21 +0200790 def test_pyobject_freed_is_freed(self):
791 self.check_pyobject_is_freed('check_pyobject_freed_is_freed')
Victor Stinner2b00db62019-04-11 11:33:27 +0200792
Victor Stinnerc4aec362016-03-14 22:26:53 +0100793
794class PyMemMallocDebugTests(PyMemDebugTests):
795 PYTHONMALLOC = 'malloc_debug'
Victor Stinner34be8072016-03-14 12:04:26 +0100796
797
Victor Stinner5d39e042017-11-29 17:20:38 +0100798@unittest.skipUnless(support.with_pymalloc(), 'need pymalloc')
Victor Stinnerc4aec362016-03-14 22:26:53 +0100799class PyMemPymallocDebugTests(PyMemDebugTests):
800 PYTHONMALLOC = 'pymalloc_debug'
Victor Stinner34be8072016-03-14 12:04:26 +0100801
802
803@unittest.skipUnless(Py_DEBUG, 'need Py_DEBUG')
Victor Stinnerc4aec362016-03-14 22:26:53 +0100804class PyMemDefaultTests(PyMemDebugTests):
805 # test default allocator of Python compiled in debug mode
806 PYTHONMALLOC = ''
Victor Stinner34be8072016-03-14 12:04:26 +0100807
808
Petr Viktorine1becf42020-05-07 15:39:59 +0200809class Test_ModuleStateAccess(unittest.TestCase):
810 """Test access to module start (PEP 573)"""
811
812 # The C part of the tests lives in _testmultiphase, in a module called
813 # _testmultiphase_meth_state_access.
814 # This module has multi-phase initialization, unlike _testcapi.
815
816 def setUp(self):
817 fullname = '_testmultiphase_meth_state_access' # XXX
818 origin = importlib.util.find_spec('_testmultiphase').origin
819 loader = importlib.machinery.ExtensionFileLoader(fullname, origin)
820 spec = importlib.util.spec_from_loader(fullname, loader)
821 module = importlib.util.module_from_spec(spec)
822 loader.exec_module(module)
823 self.module = module
824
825 def test_subclass_get_module(self):
826 """PyType_GetModule for defining_class"""
827 class StateAccessType_Subclass(self.module.StateAccessType):
828 pass
829
830 instance = StateAccessType_Subclass()
831 self.assertIs(instance.get_defining_module(), self.module)
832
833 def test_subclass_get_module_with_super(self):
834 class StateAccessType_Subclass(self.module.StateAccessType):
835 def get_defining_module(self):
836 return super().get_defining_module()
837
838 instance = StateAccessType_Subclass()
839 self.assertIs(instance.get_defining_module(), self.module)
840
841 def test_state_access(self):
842 """Checks methods defined with and without argument clinic
843
844 This tests a no-arg method (get_count) and a method with
845 both a positional and keyword argument.
846 """
847
848 a = self.module.StateAccessType()
849 b = self.module.StateAccessType()
850
851 methods = {
852 'clinic': a.increment_count_clinic,
853 'noclinic': a.increment_count_noclinic,
854 }
855
856 for name, increment_count in methods.items():
857 with self.subTest(name):
858 self.assertEqual(a.get_count(), b.get_count())
859 self.assertEqual(a.get_count(), 0)
860
861 increment_count()
862 self.assertEqual(a.get_count(), b.get_count())
863 self.assertEqual(a.get_count(), 1)
864
865 increment_count(3)
866 self.assertEqual(a.get_count(), b.get_count())
867 self.assertEqual(a.get_count(), 4)
868
869 increment_count(-2, twice=True)
870 self.assertEqual(a.get_count(), b.get_count())
871 self.assertEqual(a.get_count(), 0)
872
873 with self.assertRaises(TypeError):
874 increment_count(thrice=3)
875
876 with self.assertRaises(TypeError):
877 increment_count(1, 2, 3)
878
879
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000880if __name__ == "__main__":
Zachary Warec12f09e2013-11-11 22:47:04 -0600881 unittest.main()