blob: 55027c9cbcd43aad3ffe8bc2bd15d0f5b48c9d18 [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 Shi883bc632020-07-06 17:12:49 +080020from test.support import import_helper
Hai Shie80697d2020-05-28 06:10:27 +080021from test.support import threading_helper
xdegaye85f64302017-07-01 14:14:45 +020022from test.support.script_helper import assert_python_failure, assert_python_ok
Victor Stinner45df8202010-04-28 22:31:17 +000023try:
Stefan Krahfd24f9e2012-08-20 11:04:24 +020024 import _posixsubprocess
25except ImportError:
26 _posixsubprocess = None
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020027
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +020028# Skip this test if the _testcapi module isn't available.
Hai Shi883bc632020-07-06 17:12:49 +080029_testcapi = import_helper.import_module('_testcapi')
Tim Peters9ea17ac2001-02-02 05:57:15 +000030
Victor Stinner1ae035b2020-04-17 17:47:20 +020031import _testinternalcapi
32
Victor Stinnerefde1462015-03-21 15:04:43 +010033# Were we compiled --with-pydebug or with #define Py_DEBUG?
34Py_DEBUG = hasattr(sys, 'gettotalrefcount')
35
Benjamin Petersona54c9092009-01-13 02:11:23 +000036
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000037def testfunction(self):
38 """some doc"""
39 return self
40
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +020041
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000042class InstanceMethod:
43 id = _testcapi.instancemethod(id)
44 testfunction = _testcapi.instancemethod(testfunction)
45
46class CAPITest(unittest.TestCase):
47
48 def test_instancemethod(self):
49 inst = InstanceMethod()
50 self.assertEqual(id(inst), inst.id())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000051 self.assertTrue(inst.testfunction() is inst)
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000052 self.assertEqual(inst.testfunction.__doc__, testfunction.__doc__)
53 self.assertEqual(InstanceMethod.testfunction.__doc__, testfunction.__doc__)
54
55 InstanceMethod.testfunction.attribute = "test"
56 self.assertEqual(testfunction.attribute, "test")
57 self.assertRaises(AttributeError, setattr, inst.testfunction, "attribute", "test")
58
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000059 def test_no_FatalError_infinite_loop(self):
Antoine Pitrou77e904e2013-10-08 23:04:32 +020060 with support.SuppressCrashReport():
Ezio Melotti25a40452013-03-05 20:26:17 +020061 p = subprocess.Popen([sys.executable, "-c",
Ezio Melottie1857d92013-03-05 20:31:34 +020062 'import _testcapi;'
63 '_testcapi.crash_no_current_thread()'],
64 stdout=subprocess.PIPE,
65 stderr=subprocess.PIPE)
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000066 (out, err) = p.communicate()
67 self.assertEqual(out, b'')
68 # This used to cause an infinite loop.
Vinay Sajip73954042012-05-06 11:34:50 +010069 self.assertTrue(err.rstrip().startswith(
Victor Stinner9e5d30c2020-03-07 00:54:20 +010070 b'Fatal Python error: '
Victor Stinner23ef89d2020-03-18 02:26:04 +010071 b'PyThreadState_Get: '
Victor Stinner3026cad2020-06-01 16:02:40 +020072 b'the function must be called with the GIL held, '
73 b'but the GIL is released '
74 b'(the current Python thread state is NULL)'),
75 err)
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000076
Antoine Pitrou915605c2011-02-24 20:53:48 +000077 def test_memoryview_from_NULL_pointer(self):
78 self.assertRaises(ValueError, _testcapi.make_memoryview_from_NULL_pointer)
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000079
Martin v. Löwisaa2efcb2012-04-19 14:33:43 +020080 def test_exc_info(self):
81 raised_exception = ValueError("5")
82 new_exc = TypeError("TEST")
83 try:
84 raise raised_exception
85 except ValueError as e:
86 tb = e.__traceback__
87 orig_sys_exc_info = sys.exc_info()
88 orig_exc_info = _testcapi.set_exc_info(new_exc.__class__, new_exc, None)
89 new_sys_exc_info = sys.exc_info()
90 new_exc_info = _testcapi.set_exc_info(*orig_exc_info)
91 reset_sys_exc_info = sys.exc_info()
92
93 self.assertEqual(orig_exc_info[1], e)
94
95 self.assertSequenceEqual(orig_exc_info, (raised_exception.__class__, raised_exception, tb))
96 self.assertSequenceEqual(orig_sys_exc_info, orig_exc_info)
97 self.assertSequenceEqual(reset_sys_exc_info, orig_exc_info)
98 self.assertSequenceEqual(new_exc_info, (new_exc.__class__, new_exc, None))
99 self.assertSequenceEqual(new_sys_exc_info, new_exc_info)
100 else:
101 self.assertTrue(False)
102
Stefan Krahfd24f9e2012-08-20 11:04:24 +0200103 @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
104 def test_seq_bytes_to_charp_array(self):
105 # Issue #15732: crash in _PySequence_BytesToCharpArray()
106 class Z(object):
107 def __len__(self):
108 return 1
109 self.assertRaises(TypeError, _posixsubprocess.fork_exec,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -0700110 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 +0200111 # Issue #15736: overflow in _PySequence_BytesToCharpArray()
112 class Z(object):
113 def __len__(self):
114 return sys.maxsize
115 def __getitem__(self, i):
116 return b'x'
117 self.assertRaises(MemoryError, _posixsubprocess.fork_exec,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -0700118 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 +0200119
Stefan Krahdb579d72012-08-20 14:36:47 +0200120 @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
121 def test_subprocess_fork_exec(self):
122 class Z(object):
123 def __len__(self):
124 return 1
125
126 # Issue #15738: crash in subprocess_fork_exec()
127 self.assertRaises(TypeError, _posixsubprocess.fork_exec,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -0700128 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 +0200129
Larry Hastingsfcafe432013-11-23 17:35:48 -0800130 @unittest.skipIf(MISSING_C_DOCSTRINGS,
131 "Signature information for builtins requires docstrings")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800132 def test_docstring_signature_parsing(self):
133
134 self.assertEqual(_testcapi.no_docstring.__doc__, None)
135 self.assertEqual(_testcapi.no_docstring.__text_signature__, None)
136
Zachary Ware8ef887c2015-04-13 18:22:35 -0500137 self.assertEqual(_testcapi.docstring_empty.__doc__, None)
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800138 self.assertEqual(_testcapi.docstring_empty.__text_signature__, None)
139
140 self.assertEqual(_testcapi.docstring_no_signature.__doc__,
141 "This docstring has no signature.")
142 self.assertEqual(_testcapi.docstring_no_signature.__text_signature__, None)
143
144 self.assertEqual(_testcapi.docstring_with_invalid_signature.__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800145 "docstring_with_invalid_signature($module, /, boo)\n"
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800146 "\n"
147 "This docstring has an invalid signature."
148 )
149 self.assertEqual(_testcapi.docstring_with_invalid_signature.__text_signature__, None)
150
Larry Hastings2623c8c2014-02-08 22:15:29 -0800151 self.assertEqual(_testcapi.docstring_with_invalid_signature2.__doc__,
152 "docstring_with_invalid_signature2($module, /, boo)\n"
153 "\n"
154 "--\n"
155 "\n"
156 "This docstring also has an invalid signature."
157 )
158 self.assertEqual(_testcapi.docstring_with_invalid_signature2.__text_signature__, None)
159
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800160 self.assertEqual(_testcapi.docstring_with_signature.__doc__,
161 "This docstring has a valid signature.")
Larry Hastings2623c8c2014-02-08 22:15:29 -0800162 self.assertEqual(_testcapi.docstring_with_signature.__text_signature__, "($module, /, sig)")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800163
Zachary Ware8ef887c2015-04-13 18:22:35 -0500164 self.assertEqual(_testcapi.docstring_with_signature_but_no_doc.__doc__, None)
165 self.assertEqual(_testcapi.docstring_with_signature_but_no_doc.__text_signature__,
166 "($module, /, sig)")
167
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800168 self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800169 "\nThis docstring has a valid signature and some extra newlines.")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800170 self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__text_signature__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800171 "($module, /, parameter)")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800172
Benjamin Petersond51374e2014-04-09 23:55:56 -0400173 def test_c_type_with_matrix_multiplication(self):
174 M = _testcapi.matmulType
175 m1 = M()
176 m2 = M()
177 self.assertEqual(m1 @ m2, ("matmul", m1, m2))
178 self.assertEqual(m1 @ 42, ("matmul", m1, 42))
179 self.assertEqual(42 @ m1, ("matmul", 42, m1))
180 o = m1
181 o @= m2
182 self.assertEqual(o, ("imatmul", m1, m2))
183 o = m1
184 o @= 42
185 self.assertEqual(o, ("imatmul", m1, 42))
186 o = 42
187 o @= m1
188 self.assertEqual(o, ("matmul", 42, m1))
189
Zackery Spytzc7f803b2019-05-31 03:46:36 -0600190 def test_c_type_with_ipow(self):
191 # When the __ipow__ method of a type was implemented in C, using the
192 # modulo param would cause segfaults.
193 o = _testcapi.ipowType()
194 self.assertEqual(o.__ipow__(1), (1, None))
195 self.assertEqual(o.__ipow__(2, 2), (2, 2))
196
Victor Stinnerefde1462015-03-21 15:04:43 +0100197 def test_return_null_without_error(self):
198 # Issue #23571: A function must not return NULL without setting an
199 # error
200 if Py_DEBUG:
201 code = textwrap.dedent("""
202 import _testcapi
203 from test import support
204
205 with support.SuppressCrashReport():
206 _testcapi.return_null_without_error()
207 """)
208 rc, out, err = assert_python_failure('-c', code)
Victor Stinner381a9bc2015-03-24 14:01:32 +0100209 self.assertRegex(err.replace(b'\r', b''),
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100210 br'Fatal Python error: _Py_CheckFunctionResult: '
211 br'a function returned NULL '
Victor Stinner944fbcc2015-03-24 16:28:52 +0100212 br'without setting an error\n'
Victor Stinner1ce16fb2019-09-18 01:35:33 +0200213 br'Python runtime state: initialized\n'
Victor Stinner381a9bc2015-03-24 14:01:32 +0100214 br'SystemError: <built-in function '
215 br'return_null_without_error> returned NULL '
216 br'without setting an error\n'
217 br'\n'
218 br'Current thread.*:\n'
219 br' File .*", line 6 in <module>')
Victor Stinnerefde1462015-03-21 15:04:43 +0100220 else:
221 with self.assertRaises(SystemError) as cm:
222 _testcapi.return_null_without_error()
223 self.assertRegex(str(cm.exception),
224 'return_null_without_error.* '
225 'returned NULL without setting an error')
226
227 def test_return_result_with_error(self):
228 # Issue #23571: A function must not return a result with an error set
229 if Py_DEBUG:
230 code = textwrap.dedent("""
231 import _testcapi
232 from test import support
233
234 with support.SuppressCrashReport():
235 _testcapi.return_result_with_error()
236 """)
237 rc, out, err = assert_python_failure('-c', code)
Victor Stinner381a9bc2015-03-24 14:01:32 +0100238 self.assertRegex(err.replace(b'\r', b''),
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100239 br'Fatal Python error: _Py_CheckFunctionResult: '
240 br'a function returned a result '
241 br'with an error set\n'
Victor Stinner1ce16fb2019-09-18 01:35:33 +0200242 br'Python runtime state: initialized\n'
Victor Stinner381a9bc2015-03-24 14:01:32 +0100243 br'ValueError\n'
244 br'\n'
Serhiy Storchaka467ab192016-10-21 17:09:17 +0300245 br'The above exception was the direct cause '
246 br'of the following exception:\n'
Victor Stinner381a9bc2015-03-24 14:01:32 +0100247 br'\n'
248 br'SystemError: <built-in '
249 br'function return_result_with_error> '
250 br'returned a result with an error set\n'
251 br'\n'
252 br'Current thread.*:\n'
253 br' File .*, line 6 in <module>')
Victor Stinnerefde1462015-03-21 15:04:43 +0100254 else:
255 with self.assertRaises(SystemError) as cm:
256 _testcapi.return_result_with_error()
257 self.assertRegex(str(cm.exception),
258 'return_result_with_error.* '
259 'returned a result with an error set')
260
Serhiy Storchaka13e602e2016-05-20 22:31:14 +0300261 def test_buildvalue_N(self):
262 _testcapi.test_buildvalue_N()
263
xdegaye85f64302017-07-01 14:14:45 +0200264 def test_set_nomemory(self):
265 code = """if 1:
266 import _testcapi
267
268 class C(): pass
269
270 # The first loop tests both functions and that remove_mem_hooks()
271 # can be called twice in a row. The second loop checks a call to
272 # set_nomemory() after a call to remove_mem_hooks(). The third
273 # loop checks the start and stop arguments of set_nomemory().
274 for outer_cnt in range(1, 4):
275 start = 10 * outer_cnt
276 for j in range(100):
277 if j == 0:
278 if outer_cnt != 3:
279 _testcapi.set_nomemory(start)
280 else:
281 _testcapi.set_nomemory(start, start + 1)
282 try:
283 C()
284 except MemoryError as e:
285 if outer_cnt != 3:
286 _testcapi.remove_mem_hooks()
287 print('MemoryError', outer_cnt, j)
288 _testcapi.remove_mem_hooks()
289 break
290 """
291 rc, out, err = assert_python_ok('-c', code)
292 self.assertIn(b'MemoryError 1 10', out)
293 self.assertIn(b'MemoryError 2 20', out)
294 self.assertIn(b'MemoryError 3 30', out)
295
Oren Milman0ccc0f62017-10-08 11:17:46 +0300296 def test_mapping_keys_values_items(self):
297 class Mapping1(dict):
298 def keys(self):
299 return list(super().keys())
300 def values(self):
301 return list(super().values())
302 def items(self):
303 return list(super().items())
304 class Mapping2(dict):
305 def keys(self):
306 return tuple(super().keys())
307 def values(self):
308 return tuple(super().values())
309 def items(self):
310 return tuple(super().items())
311 dict_obj = {'foo': 1, 'bar': 2, 'spam': 3}
312
313 for mapping in [{}, OrderedDict(), Mapping1(), Mapping2(),
314 dict_obj, OrderedDict(dict_obj),
315 Mapping1(dict_obj), Mapping2(dict_obj)]:
316 self.assertListEqual(_testcapi.get_mapping_keys(mapping),
317 list(mapping.keys()))
318 self.assertListEqual(_testcapi.get_mapping_values(mapping),
319 list(mapping.values()))
320 self.assertListEqual(_testcapi.get_mapping_items(mapping),
321 list(mapping.items()))
322
323 def test_mapping_keys_values_items_bad_arg(self):
324 self.assertRaises(AttributeError, _testcapi.get_mapping_keys, None)
325 self.assertRaises(AttributeError, _testcapi.get_mapping_values, None)
326 self.assertRaises(AttributeError, _testcapi.get_mapping_items, None)
327
328 class BadMapping:
329 def keys(self):
330 return None
331 def values(self):
332 return None
333 def items(self):
334 return None
335 bad_mapping = BadMapping()
336 self.assertRaises(TypeError, _testcapi.get_mapping_keys, bad_mapping)
337 self.assertRaises(TypeError, _testcapi.get_mapping_values, bad_mapping)
338 self.assertRaises(TypeError, _testcapi.get_mapping_items, bad_mapping)
339
Victor Stinner18618e652018-10-25 17:28:11 +0200340 @unittest.skipUnless(hasattr(_testcapi, 'negative_refcount'),
341 'need _testcapi.negative_refcount')
342 def test_negative_refcount(self):
343 # bpo-35059: Check that Py_DECREF() reports the correct filename
344 # when calling _Py_NegativeRefcount() to abort Python.
345 code = textwrap.dedent("""
346 import _testcapi
347 from test import support
348
349 with support.SuppressCrashReport():
350 _testcapi.negative_refcount()
351 """)
352 rc, out, err = assert_python_failure('-c', code)
353 self.assertRegex(err,
Victor Stinner3ec9af72018-10-26 02:12:34 +0200354 br'_testcapimodule\.c:[0-9]+: '
Victor Stinnerf1d002c2018-11-21 23:53:44 +0100355 br'_Py_NegativeRefcount: Assertion failed: '
Victor Stinner3ec9af72018-10-26 02:12:34 +0200356 br'object has negative ref count')
Victor Stinner18618e652018-10-25 17:28:11 +0200357
Jeroen Demeyer351c6742019-05-10 19:21:11 +0200358 def test_trashcan_subclass(self):
359 # bpo-35983: Check that the trashcan mechanism for "list" is NOT
360 # activated when its tp_dealloc is being called by a subclass
361 from _testcapi import MyList
362 L = None
363 for i in range(1000):
364 L = MyList((L,))
365
Victor Stinner0127bb12019-11-21 12:54:02 +0100366 @support.requires_resource('cpu')
Jeroen Demeyer351c6742019-05-10 19:21:11 +0200367 def test_trashcan_python_class1(self):
368 self.do_test_trashcan_python_class(list)
369
Victor Stinner0127bb12019-11-21 12:54:02 +0100370 @support.requires_resource('cpu')
Jeroen Demeyer351c6742019-05-10 19:21:11 +0200371 def test_trashcan_python_class2(self):
372 from _testcapi import MyList
373 self.do_test_trashcan_python_class(MyList)
374
375 def do_test_trashcan_python_class(self, base):
376 # Check that the trashcan mechanism works properly for a Python
377 # subclass of a class using the trashcan (this specific test assumes
378 # that the base class "base" behaves like list)
379 class PyList(base):
380 # Count the number of PyList instances to verify that there is
381 # no memory leak
382 num = 0
383 def __init__(self, *args):
384 __class__.num += 1
385 super().__init__(*args)
386 def __del__(self):
387 __class__.num -= 1
388
389 for parity in (0, 1):
390 L = None
391 # We need in the order of 2**20 iterations here such that a
392 # typical 8MB stack would overflow without the trashcan.
393 for i in range(2**20):
394 L = PyList((L,))
395 L.attr = i
396 if parity:
397 # Add one additional nesting layer
398 L = (L,)
399 self.assertGreater(PyList.num, 0)
400 del L
401 self.assertEqual(PyList.num, 0)
402
Eddie Elizondoff023ed2019-09-11 05:17:13 -0400403 def test_subclass_of_heap_gc_ctype_with_tpdealloc_decrefs_once(self):
404 class HeapGcCTypeSubclass(_testcapi.HeapGcCType):
405 def __init__(self):
406 self.value2 = 20
407 super().__init__()
408
409 subclass_instance = HeapGcCTypeSubclass()
410 type_refcnt = sys.getrefcount(HeapGcCTypeSubclass)
411
412 # Test that subclass instance was fully created
413 self.assertEqual(subclass_instance.value, 10)
414 self.assertEqual(subclass_instance.value2, 20)
415
416 # Test that the type reference count is only decremented once
417 del subclass_instance
418 self.assertEqual(type_refcnt - 1, sys.getrefcount(HeapGcCTypeSubclass))
419
420 def test_subclass_of_heap_gc_ctype_with_del_modifying_dunder_class_only_decrefs_once(self):
421 class A(_testcapi.HeapGcCType):
422 def __init__(self):
423 self.value2 = 20
424 super().__init__()
425
426 class B(A):
427 def __init__(self):
428 super().__init__()
429
430 def __del__(self):
431 self.__class__ = A
432 A.refcnt_in_del = sys.getrefcount(A)
433 B.refcnt_in_del = sys.getrefcount(B)
434
435 subclass_instance = B()
436 type_refcnt = sys.getrefcount(B)
437 new_type_refcnt = sys.getrefcount(A)
438
439 # Test that subclass instance was fully created
440 self.assertEqual(subclass_instance.value, 10)
441 self.assertEqual(subclass_instance.value2, 20)
442
443 del subclass_instance
444
445 # Test that setting __class__ modified the reference counts of the types
446 self.assertEqual(type_refcnt - 1, B.refcnt_in_del)
447 self.assertEqual(new_type_refcnt + 1, A.refcnt_in_del)
448
449 # Test that the original type already has decreased its refcnt
450 self.assertEqual(type_refcnt - 1, sys.getrefcount(B))
451
452 # Test that subtype_dealloc decref the newly assigned __class__ only once
453 self.assertEqual(new_type_refcnt, sys.getrefcount(A))
454
Eddie Elizondo3368f3c2019-09-19 09:29:05 -0700455 def test_heaptype_with_dict(self):
456 inst = _testcapi.HeapCTypeWithDict()
457 inst.foo = 42
458 self.assertEqual(inst.foo, 42)
459 self.assertEqual(inst.dictobj, inst.__dict__)
460 self.assertEqual(inst.dictobj, {"foo": 42})
461
462 inst = _testcapi.HeapCTypeWithDict()
463 self.assertEqual({}, inst.__dict__)
464
465 def test_heaptype_with_negative_dict(self):
466 inst = _testcapi.HeapCTypeWithNegativeDict()
467 inst.foo = 42
468 self.assertEqual(inst.foo, 42)
469 self.assertEqual(inst.dictobj, inst.__dict__)
470 self.assertEqual(inst.dictobj, {"foo": 42})
471
472 inst = _testcapi.HeapCTypeWithNegativeDict()
473 self.assertEqual({}, inst.__dict__)
474
475 def test_heaptype_with_weakref(self):
476 inst = _testcapi.HeapCTypeWithWeakref()
477 ref = weakref.ref(inst)
478 self.assertEqual(ref(), inst)
479 self.assertEqual(inst.weakreflist, ref)
480
scoderf7c4e232020-06-06 21:35:10 +0200481 def test_heaptype_with_buffer(self):
482 inst = _testcapi.HeapCTypeWithBuffer()
483 b = bytes(inst)
484 self.assertEqual(b, b"1234")
485
Eddie Elizondoff023ed2019-09-11 05:17:13 -0400486 def test_c_subclass_of_heap_ctype_with_tpdealloc_decrefs_once(self):
487 subclass_instance = _testcapi.HeapCTypeSubclass()
488 type_refcnt = sys.getrefcount(_testcapi.HeapCTypeSubclass)
489
490 # Test that subclass instance was fully created
491 self.assertEqual(subclass_instance.value, 10)
492 self.assertEqual(subclass_instance.value2, 20)
493
494 # Test that the type reference count is only decremented once
495 del subclass_instance
496 self.assertEqual(type_refcnt - 1, sys.getrefcount(_testcapi.HeapCTypeSubclass))
497
498 def test_c_subclass_of_heap_ctype_with_del_modifying_dunder_class_only_decrefs_once(self):
499 subclass_instance = _testcapi.HeapCTypeSubclassWithFinalizer()
500 type_refcnt = sys.getrefcount(_testcapi.HeapCTypeSubclassWithFinalizer)
501 new_type_refcnt = sys.getrefcount(_testcapi.HeapCTypeSubclass)
502
503 # Test that subclass instance was fully created
504 self.assertEqual(subclass_instance.value, 10)
505 self.assertEqual(subclass_instance.value2, 20)
506
507 # The tp_finalize slot will set __class__ to HeapCTypeSubclass
508 del subclass_instance
509
510 # Test that setting __class__ modified the reference counts of the types
511 self.assertEqual(type_refcnt - 1, _testcapi.HeapCTypeSubclassWithFinalizer.refcnt_in_del)
512 self.assertEqual(new_type_refcnt + 1, _testcapi.HeapCTypeSubclass.refcnt_in_del)
513
514 # Test that the original type already has decreased its refcnt
515 self.assertEqual(type_refcnt - 1, sys.getrefcount(_testcapi.HeapCTypeSubclassWithFinalizer))
516
517 # Test that subtype_dealloc decref the newly assigned __class__ only once
518 self.assertEqual(new_type_refcnt, sys.getrefcount(_testcapi.HeapCTypeSubclass))
519
scoder148f3292020-07-03 02:09:28 +0200520 def test_heaptype_with_setattro(self):
521 obj = _testcapi.HeapCTypeSetattr()
522 self.assertEqual(obj.pvalue, 10)
523 obj.value = 12
524 self.assertEqual(obj.pvalue, 12)
525 del obj.value
526 self.assertEqual(obj.pvalue, 0)
527
Serhiy Storchakae5ccc942020-03-09 20:03:38 +0200528 def test_pynumber_tobase(self):
529 from _testcapi import pynumber_tobase
530 self.assertEqual(pynumber_tobase(123, 2), '0b1111011')
531 self.assertEqual(pynumber_tobase(123, 8), '0o173')
532 self.assertEqual(pynumber_tobase(123, 10), '123')
533 self.assertEqual(pynumber_tobase(123, 16), '0x7b')
534 self.assertEqual(pynumber_tobase(-123, 2), '-0b1111011')
535 self.assertEqual(pynumber_tobase(-123, 8), '-0o173')
536 self.assertEqual(pynumber_tobase(-123, 10), '-123')
537 self.assertEqual(pynumber_tobase(-123, 16), '-0x7b')
538 self.assertRaises(TypeError, pynumber_tobase, 123.0, 10)
539 self.assertRaises(TypeError, pynumber_tobase, '123', 10)
540 self.assertRaises(SystemError, pynumber_tobase, 123, 0)
541
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800542
Benjamin Petersona54c9092009-01-13 02:11:23 +0000543class TestPendingCalls(unittest.TestCase):
544
545 def pendingcalls_submit(self, l, n):
546 def callback():
547 #this function can be interrupted by thread switching so let's
548 #use an atomic operation
549 l.append(None)
550
551 for i in range(n):
552 time.sleep(random.random()*0.02) #0.01 secs on average
553 #try submitting callback until successful.
554 #rely on regular interrupt to flush queue if we are
555 #unsuccessful.
556 while True:
557 if _testcapi._pending_threadfunc(callback):
558 break;
559
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000560 def pendingcalls_wait(self, l, n, context = None):
Benjamin Petersona54c9092009-01-13 02:11:23 +0000561 #now, stick around until l[0] has grown to 10
562 count = 0;
563 while len(l) != n:
564 #this busy loop is where we expect to be interrupted to
565 #run our callbacks. Note that callbacks are only run on the
566 #main thread
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 for i in range(1000):
570 a = i*i
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000571 if context and not context.event.is_set():
572 continue
Benjamin Petersona54c9092009-01-13 02:11:23 +0000573 count += 1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000574 self.assertTrue(count < 10000,
Benjamin Petersona54c9092009-01-13 02:11:23 +0000575 "timeout waiting for %i callbacks, got %i"%(n, len(l)))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000576 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +0000577 print("(%i)"%(len(l),))
578
579 def test_pendingcalls_threaded(self):
Benjamin Petersona54c9092009-01-13 02:11:23 +0000580
581 #do every callback on a separate thread
Victor Stinnere225beb2019-06-03 18:14:24 +0200582 n = 32 #total callbacks
Benjamin Petersona54c9092009-01-13 02:11:23 +0000583 threads = []
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000584 class foo(object):pass
585 context = foo()
586 context.l = []
587 context.n = 2 #submits per thread
588 context.nThreads = n // context.n
589 context.nFinished = 0
590 context.lock = threading.Lock()
591 context.event = threading.Event()
592
Serhiy Storchaka263dcd22015-04-01 13:01:14 +0300593 threads = [threading.Thread(target=self.pendingcalls_thread,
594 args=(context,))
595 for i in range(context.nThreads)]
Hai Shie80697d2020-05-28 06:10:27 +0800596 with threading_helper.start_threads(threads):
Serhiy Storchaka263dcd22015-04-01 13:01:14 +0300597 self.pendingcalls_wait(context.l, n, context)
Benjamin Petersona54c9092009-01-13 02:11:23 +0000598
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000599 def pendingcalls_thread(self, context):
600 try:
601 self.pendingcalls_submit(context.l, context.n)
602 finally:
603 with context.lock:
604 context.nFinished += 1
605 nFinished = context.nFinished
606 if False and support.verbose:
607 print("finished threads: ", nFinished)
608 if nFinished == context.nThreads:
609 context.event.set()
610
Benjamin Petersona54c9092009-01-13 02:11:23 +0000611 def test_pendingcalls_non_threaded(self):
Ezio Melotti13925002011-03-16 11:05:33 +0200612 #again, just using the main thread, likely they will all be dispatched at
Benjamin Petersona54c9092009-01-13 02:11:23 +0000613 #once. It is ok to ask for too many, because we loop until we find a slot.
614 #the loop can be interrupted to dispatch.
615 #there are only 32 dispatch slots, so we go for twice that!
616 l = []
617 n = 64
618 self.pendingcalls_submit(l, n)
619 self.pendingcalls_wait(l, n)
620
Antoine Pitrou7a2572c2013-08-01 20:43:26 +0200621
622class SubinterpreterTest(unittest.TestCase):
623
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100624 def test_subinterps(self):
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100625 import builtins
626 r, w = os.pipe()
627 code = """if 1:
628 import sys, builtins, pickle
629 with open({:d}, "wb") as f:
630 pickle.dump(id(sys.modules), f)
631 pickle.dump(id(builtins), f)
632 """.format(w)
633 with open(r, "rb") as f:
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100634 ret = support.run_in_subinterp(code)
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100635 self.assertEqual(ret, 0)
636 self.assertNotEqual(pickle.load(f), id(sys.modules))
637 self.assertNotEqual(pickle.load(f), id(builtins))
638
Guido van Rossum9d197c72020-06-27 17:33:49 -0700639 def test_subinterps_recent_language_features(self):
640 r, w = os.pipe()
641 code = """if 1:
642 import pickle
643 with open({:d}, "wb") as f:
644
645 @(lambda x:x) # Py 3.9
646 def noop(x): return x
647
648 a = (b := f'1{{2}}3') + noop('x') # Py 3.8 (:=) / 3.6 (f'')
649
650 async def foo(arg): return await arg # Py 3.5
651
652 pickle.dump(dict(a=a, b=b), f)
653 """.format(w)
654
655 with open(r, "rb") as f:
656 ret = support.run_in_subinterp(code)
657 self.assertEqual(ret, 0)
658 self.assertEqual(pickle.load(f), {'a': '123x', 'b': '123'})
659
Marcel Plch33e71e02019-05-22 13:51:26 +0200660 def test_mutate_exception(self):
661 """
662 Exceptions saved in global module state get shared between
663 individual module instances. This test checks whether or not
664 a change in one interpreter's module gets reflected into the
665 other ones.
666 """
667 import binascii
668
669 support.run_in_subinterp("import binascii; binascii.Error.foobar = 'foobar'")
670
671 self.assertFalse(hasattr(binascii.Error, "foobar"))
672
Antoine Pitrou7a2572c2013-08-01 20:43:26 +0200673
Ezio Melotti29267c82013-02-23 05:52:46 +0200674class TestThreadState(unittest.TestCase):
675
Hai Shie80697d2020-05-28 06:10:27 +0800676 @threading_helper.reap_threads
Ezio Melotti29267c82013-02-23 05:52:46 +0200677 def test_thread_state(self):
678 # some extra thread-state tests driven via _testcapi
679 def target():
680 idents = []
681
682 def callback():
Ezio Melotti35246bd2013-02-23 05:58:38 +0200683 idents.append(threading.get_ident())
Ezio Melotti29267c82013-02-23 05:52:46 +0200684
685 _testcapi._test_thread_state(callback)
686 a = b = callback
687 time.sleep(1)
688 # Check our main thread is in the list exactly 3 times.
Ezio Melotti35246bd2013-02-23 05:58:38 +0200689 self.assertEqual(idents.count(threading.get_ident()), 3,
Ezio Melotti29267c82013-02-23 05:52:46 +0200690 "Couldn't find main thread correctly in the list")
691
692 target()
693 t = threading.Thread(target=target)
694 t.start()
695 t.join()
696
Victor Stinner34be8072016-03-14 12:04:26 +0100697
Zachary Warec12f09e2013-11-11 22:47:04 -0600698class Test_testcapi(unittest.TestCase):
Serhiy Storchaka8f7bb102018-08-06 16:50:19 +0300699 locals().update((name, getattr(_testcapi, name))
700 for name in dir(_testcapi)
701 if name.startswith('test_') and not name.endswith('_code'))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000702
Victor Stinner34be8072016-03-14 12:04:26 +0100703
Victor Stinner1ae035b2020-04-17 17:47:20 +0200704class Test_testinternalcapi(unittest.TestCase):
705 locals().update((name, getattr(_testinternalcapi, name))
706 for name in dir(_testinternalcapi)
707 if name.startswith('test_'))
708
709
Victor Stinnerc4aec362016-03-14 22:26:53 +0100710class PyMemDebugTests(unittest.TestCase):
711 PYTHONMALLOC = 'debug'
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100712 # '0x04c06e0' or '04C06E0'
Victor Stinner08572f62016-03-14 21:55:43 +0100713 PTR_REGEX = r'(?:0x)?[0-9a-fA-F]+'
Victor Stinner34be8072016-03-14 12:04:26 +0100714
715 def check(self, code):
716 with support.SuppressCrashReport():
Victor Stinnerc4aec362016-03-14 22:26:53 +0100717 out = assert_python_failure('-c', code,
718 PYTHONMALLOC=self.PYTHONMALLOC)
Victor Stinner34be8072016-03-14 12:04:26 +0100719 stderr = out.err
720 return stderr.decode('ascii', 'replace')
721
722 def test_buffer_overflow(self):
723 out = self.check('import _testcapi; _testcapi.pymem_buffer_overflow()')
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100724 regex = (r"Debug memory block at address p={ptr}: API 'm'\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100725 r" 16 bytes originally requested\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100726 r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n"
727 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 +0100728 r" at tail\+0: 0x78 \*\*\* OUCH\n"
Victor Stinner4c409be2019-04-11 13:01:15 +0200729 r" at tail\+1: 0xfd\n"
730 r" at tail\+2: 0xfd\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100731 r" .*\n"
Victor Stinnere8f9acf2019-04-12 21:54:06 +0200732 r"( The block was made by call #[0-9]+ to debug malloc/realloc.\n)?"
Victor Stinner4c409be2019-04-11 13:01:15 +0200733 r" Data at p: cd cd cd .*\n"
Victor Stinner6453e9e2016-03-15 23:36:28 +0100734 r"\n"
Victor Stinnerf966e532018-11-13 15:14:58 +0100735 r"Enable tracemalloc to get the memory block allocation traceback\n"
736 r"\n"
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100737 r"Fatal Python error: _PyMem_DebugRawFree: bad trailing pad byte")
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100738 regex = regex.format(ptr=self.PTR_REGEX)
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100739 regex = re.compile(regex, flags=re.DOTALL)
Victor Stinner34be8072016-03-14 12:04:26 +0100740 self.assertRegex(out, regex)
741
742 def test_api_misuse(self):
743 out = self.check('import _testcapi; _testcapi.pymem_api_misuse()')
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100744 regex = (r"Debug memory block at address p={ptr}: API 'm'\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100745 r" 16 bytes originally requested\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100746 r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n"
747 r" The [0-9] pad bytes at tail={ptr} are FORBIDDENBYTE, as expected.\n"
Victor Stinnere8f9acf2019-04-12 21:54:06 +0200748 r"( The block was made by call #[0-9]+ to debug malloc/realloc.\n)?"
Victor Stinner4c409be2019-04-11 13:01:15 +0200749 r" Data at p: cd cd cd .*\n"
Victor Stinner6453e9e2016-03-15 23:36:28 +0100750 r"\n"
Victor Stinnerf966e532018-11-13 15:14:58 +0100751 r"Enable tracemalloc to get the memory block allocation traceback\n"
752 r"\n"
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100753 r"Fatal Python error: _PyMem_DebugRawFree: bad ID: Allocated using API 'm', verified using API 'r'\n")
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100754 regex = regex.format(ptr=self.PTR_REGEX)
Victor Stinner34be8072016-03-14 12:04:26 +0100755 self.assertRegex(out, regex)
756
Victor Stinnerad524372016-03-16 12:12:53 +0100757 def check_malloc_without_gil(self, code):
Victor Stinnerc4aec362016-03-14 22:26:53 +0100758 out = self.check(code)
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100759 expected = ('Fatal Python error: _PyMem_DebugMalloc: '
760 'Python memory allocator called without holding the GIL')
Victor Stinnerc4aec362016-03-14 22:26:53 +0100761 self.assertIn(expected, out)
Victor Stinner34be8072016-03-14 12:04:26 +0100762
Victor Stinnerad524372016-03-16 12:12:53 +0100763 def test_pymem_malloc_without_gil(self):
764 # Debug hooks must raise an error if PyMem_Malloc() is called
765 # without holding the GIL
766 code = 'import _testcapi; _testcapi.pymem_malloc_without_gil()'
767 self.check_malloc_without_gil(code)
768
769 def test_pyobject_malloc_without_gil(self):
770 # Debug hooks must raise an error if PyObject_Malloc() is called
771 # without holding the GIL
772 code = 'import _testcapi; _testcapi.pyobject_malloc_without_gil()'
773 self.check_malloc_without_gil(code)
774
Victor Stinner3bf0f3a2019-06-07 16:22:21 +0200775 def check_pyobject_is_freed(self, func_name):
776 code = textwrap.dedent(f'''
Victor Stinner2b00db62019-04-11 11:33:27 +0200777 import gc, os, sys, _testcapi
778 # Disable the GC to avoid crash on GC collection
779 gc.disable()
Victor Stinner3bf0f3a2019-06-07 16:22:21 +0200780 try:
781 _testcapi.{func_name}()
782 # Exit immediately to avoid a crash while deallocating
783 # the invalid object
784 os._exit(0)
785 except _testcapi.error:
786 os._exit(1)
Victor Stinner2b00db62019-04-11 11:33:27 +0200787 ''')
Victor Stinner2b00db62019-04-11 11:33:27 +0200788 assert_python_ok('-c', code, PYTHONMALLOC=self.PYTHONMALLOC)
789
Victor Stinner68762572019-10-07 18:42:01 +0200790 def test_pyobject_null_is_freed(self):
791 self.check_pyobject_is_freed('check_pyobject_null_is_freed')
792
Victor Stinner3bf0f3a2019-06-07 16:22:21 +0200793 def test_pyobject_uninitialized_is_freed(self):
794 self.check_pyobject_is_freed('check_pyobject_uninitialized_is_freed')
Victor Stinner2b00db62019-04-11 11:33:27 +0200795
Victor Stinner3bf0f3a2019-06-07 16:22:21 +0200796 def test_pyobject_forbidden_bytes_is_freed(self):
797 self.check_pyobject_is_freed('check_pyobject_forbidden_bytes_is_freed')
Victor Stinner2b00db62019-04-11 11:33:27 +0200798
Victor Stinner3bf0f3a2019-06-07 16:22:21 +0200799 def test_pyobject_freed_is_freed(self):
800 self.check_pyobject_is_freed('check_pyobject_freed_is_freed')
Victor Stinner2b00db62019-04-11 11:33:27 +0200801
Victor Stinnerc4aec362016-03-14 22:26:53 +0100802
803class PyMemMallocDebugTests(PyMemDebugTests):
804 PYTHONMALLOC = 'malloc_debug'
Victor Stinner34be8072016-03-14 12:04:26 +0100805
806
Victor Stinner5d39e042017-11-29 17:20:38 +0100807@unittest.skipUnless(support.with_pymalloc(), 'need pymalloc')
Victor Stinnerc4aec362016-03-14 22:26:53 +0100808class PyMemPymallocDebugTests(PyMemDebugTests):
809 PYTHONMALLOC = 'pymalloc_debug'
Victor Stinner34be8072016-03-14 12:04:26 +0100810
811
812@unittest.skipUnless(Py_DEBUG, 'need Py_DEBUG')
Victor Stinnerc4aec362016-03-14 22:26:53 +0100813class PyMemDefaultTests(PyMemDebugTests):
814 # test default allocator of Python compiled in debug mode
815 PYTHONMALLOC = ''
Victor Stinner34be8072016-03-14 12:04:26 +0100816
817
Petr Viktorine1becf42020-05-07 15:39:59 +0200818class Test_ModuleStateAccess(unittest.TestCase):
819 """Test access to module start (PEP 573)"""
820
821 # The C part of the tests lives in _testmultiphase, in a module called
822 # _testmultiphase_meth_state_access.
823 # This module has multi-phase initialization, unlike _testcapi.
824
825 def setUp(self):
826 fullname = '_testmultiphase_meth_state_access' # XXX
827 origin = importlib.util.find_spec('_testmultiphase').origin
828 loader = importlib.machinery.ExtensionFileLoader(fullname, origin)
829 spec = importlib.util.spec_from_loader(fullname, loader)
830 module = importlib.util.module_from_spec(spec)
831 loader.exec_module(module)
832 self.module = module
833
834 def test_subclass_get_module(self):
835 """PyType_GetModule for defining_class"""
836 class StateAccessType_Subclass(self.module.StateAccessType):
837 pass
838
839 instance = StateAccessType_Subclass()
840 self.assertIs(instance.get_defining_module(), self.module)
841
842 def test_subclass_get_module_with_super(self):
843 class StateAccessType_Subclass(self.module.StateAccessType):
844 def get_defining_module(self):
845 return super().get_defining_module()
846
847 instance = StateAccessType_Subclass()
848 self.assertIs(instance.get_defining_module(), self.module)
849
850 def test_state_access(self):
851 """Checks methods defined with and without argument clinic
852
853 This tests a no-arg method (get_count) and a method with
854 both a positional and keyword argument.
855 """
856
857 a = self.module.StateAccessType()
858 b = self.module.StateAccessType()
859
860 methods = {
861 'clinic': a.increment_count_clinic,
862 'noclinic': a.increment_count_noclinic,
863 }
864
865 for name, increment_count in methods.items():
866 with self.subTest(name):
867 self.assertEqual(a.get_count(), b.get_count())
868 self.assertEqual(a.get_count(), 0)
869
870 increment_count()
871 self.assertEqual(a.get_count(), b.get_count())
872 self.assertEqual(a.get_count(), 1)
873
874 increment_count(3)
875 self.assertEqual(a.get_count(), b.get_count())
876 self.assertEqual(a.get_count(), 4)
877
878 increment_count(-2, twice=True)
879 self.assertEqual(a.get_count(), b.get_count())
880 self.assertEqual(a.get_count(), 0)
881
882 with self.assertRaises(TypeError):
883 increment_count(thrice=3)
884
885 with self.assertRaises(TypeError):
886 increment_count(1, 2, 3)
887
888
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000889if __name__ == "__main__":
Zachary Warec12f09e2013-11-11 22:47:04 -0600890 unittest.main()