blob: 44693b8fdd7178ffad7bb984de1074b3f4b87fce [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: '
71 b'current thread state is NULL (released GIL?)'))
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000072
Antoine Pitrou915605c2011-02-24 20:53:48 +000073 def test_memoryview_from_NULL_pointer(self):
74 self.assertRaises(ValueError, _testcapi.make_memoryview_from_NULL_pointer)
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000075
Martin v. Löwisaa2efcb2012-04-19 14:33:43 +020076 def test_exc_info(self):
77 raised_exception = ValueError("5")
78 new_exc = TypeError("TEST")
79 try:
80 raise raised_exception
81 except ValueError as e:
82 tb = e.__traceback__
83 orig_sys_exc_info = sys.exc_info()
84 orig_exc_info = _testcapi.set_exc_info(new_exc.__class__, new_exc, None)
85 new_sys_exc_info = sys.exc_info()
86 new_exc_info = _testcapi.set_exc_info(*orig_exc_info)
87 reset_sys_exc_info = sys.exc_info()
88
89 self.assertEqual(orig_exc_info[1], e)
90
91 self.assertSequenceEqual(orig_exc_info, (raised_exception.__class__, raised_exception, tb))
92 self.assertSequenceEqual(orig_sys_exc_info, orig_exc_info)
93 self.assertSequenceEqual(reset_sys_exc_info, orig_exc_info)
94 self.assertSequenceEqual(new_exc_info, (new_exc.__class__, new_exc, None))
95 self.assertSequenceEqual(new_sys_exc_info, new_exc_info)
96 else:
97 self.assertTrue(False)
98
Stefan Krahfd24f9e2012-08-20 11:04:24 +020099 @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
100 def test_seq_bytes_to_charp_array(self):
101 # Issue #15732: crash in _PySequence_BytesToCharpArray()
102 class Z(object):
103 def __len__(self):
104 return 1
105 self.assertRaises(TypeError, _posixsubprocess.fork_exec,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -0700106 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 +0200107 # Issue #15736: overflow in _PySequence_BytesToCharpArray()
108 class Z(object):
109 def __len__(self):
110 return sys.maxsize
111 def __getitem__(self, i):
112 return b'x'
113 self.assertRaises(MemoryError, _posixsubprocess.fork_exec,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -0700114 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 +0200115
Stefan Krahdb579d72012-08-20 14:36:47 +0200116 @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
117 def test_subprocess_fork_exec(self):
118 class Z(object):
119 def __len__(self):
120 return 1
121
122 # Issue #15738: crash in subprocess_fork_exec()
123 self.assertRaises(TypeError, _posixsubprocess.fork_exec,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -0700124 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 +0200125
Larry Hastingsfcafe432013-11-23 17:35:48 -0800126 @unittest.skipIf(MISSING_C_DOCSTRINGS,
127 "Signature information for builtins requires docstrings")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800128 def test_docstring_signature_parsing(self):
129
130 self.assertEqual(_testcapi.no_docstring.__doc__, None)
131 self.assertEqual(_testcapi.no_docstring.__text_signature__, None)
132
Zachary Ware8ef887c2015-04-13 18:22:35 -0500133 self.assertEqual(_testcapi.docstring_empty.__doc__, None)
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800134 self.assertEqual(_testcapi.docstring_empty.__text_signature__, None)
135
136 self.assertEqual(_testcapi.docstring_no_signature.__doc__,
137 "This docstring has no signature.")
138 self.assertEqual(_testcapi.docstring_no_signature.__text_signature__, None)
139
140 self.assertEqual(_testcapi.docstring_with_invalid_signature.__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800141 "docstring_with_invalid_signature($module, /, boo)\n"
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800142 "\n"
143 "This docstring has an invalid signature."
144 )
145 self.assertEqual(_testcapi.docstring_with_invalid_signature.__text_signature__, None)
146
Larry Hastings2623c8c2014-02-08 22:15:29 -0800147 self.assertEqual(_testcapi.docstring_with_invalid_signature2.__doc__,
148 "docstring_with_invalid_signature2($module, /, boo)\n"
149 "\n"
150 "--\n"
151 "\n"
152 "This docstring also has an invalid signature."
153 )
154 self.assertEqual(_testcapi.docstring_with_invalid_signature2.__text_signature__, None)
155
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800156 self.assertEqual(_testcapi.docstring_with_signature.__doc__,
157 "This docstring has a valid signature.")
Larry Hastings2623c8c2014-02-08 22:15:29 -0800158 self.assertEqual(_testcapi.docstring_with_signature.__text_signature__, "($module, /, sig)")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800159
Zachary Ware8ef887c2015-04-13 18:22:35 -0500160 self.assertEqual(_testcapi.docstring_with_signature_but_no_doc.__doc__, None)
161 self.assertEqual(_testcapi.docstring_with_signature_but_no_doc.__text_signature__,
162 "($module, /, sig)")
163
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800164 self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800165 "\nThis docstring has a valid signature and some extra newlines.")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800166 self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__text_signature__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800167 "($module, /, parameter)")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800168
Benjamin Petersond51374e2014-04-09 23:55:56 -0400169 def test_c_type_with_matrix_multiplication(self):
170 M = _testcapi.matmulType
171 m1 = M()
172 m2 = M()
173 self.assertEqual(m1 @ m2, ("matmul", m1, m2))
174 self.assertEqual(m1 @ 42, ("matmul", m1, 42))
175 self.assertEqual(42 @ m1, ("matmul", 42, m1))
176 o = m1
177 o @= m2
178 self.assertEqual(o, ("imatmul", m1, m2))
179 o = m1
180 o @= 42
181 self.assertEqual(o, ("imatmul", m1, 42))
182 o = 42
183 o @= m1
184 self.assertEqual(o, ("matmul", 42, m1))
185
Zackery Spytzc7f803b2019-05-31 03:46:36 -0600186 def test_c_type_with_ipow(self):
187 # When the __ipow__ method of a type was implemented in C, using the
188 # modulo param would cause segfaults.
189 o = _testcapi.ipowType()
190 self.assertEqual(o.__ipow__(1), (1, None))
191 self.assertEqual(o.__ipow__(2, 2), (2, 2))
192
Victor Stinnerefde1462015-03-21 15:04:43 +0100193 def test_return_null_without_error(self):
194 # Issue #23571: A function must not return NULL without setting an
195 # error
196 if Py_DEBUG:
197 code = textwrap.dedent("""
198 import _testcapi
199 from test import support
200
201 with support.SuppressCrashReport():
202 _testcapi.return_null_without_error()
203 """)
204 rc, out, err = assert_python_failure('-c', code)
Victor Stinner381a9bc2015-03-24 14:01:32 +0100205 self.assertRegex(err.replace(b'\r', b''),
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100206 br'Fatal Python error: _Py_CheckFunctionResult: '
207 br'a function returned NULL '
Victor Stinner944fbcc2015-03-24 16:28:52 +0100208 br'without setting an error\n'
Victor Stinner1ce16fb2019-09-18 01:35:33 +0200209 br'Python runtime state: initialized\n'
Victor Stinner381a9bc2015-03-24 14:01:32 +0100210 br'SystemError: <built-in function '
211 br'return_null_without_error> returned NULL '
212 br'without setting an error\n'
213 br'\n'
214 br'Current thread.*:\n'
215 br' File .*", line 6 in <module>')
Victor Stinnerefde1462015-03-21 15:04:43 +0100216 else:
217 with self.assertRaises(SystemError) as cm:
218 _testcapi.return_null_without_error()
219 self.assertRegex(str(cm.exception),
220 'return_null_without_error.* '
221 'returned NULL without setting an error')
222
223 def test_return_result_with_error(self):
224 # Issue #23571: A function must not return a result with an error set
225 if Py_DEBUG:
226 code = textwrap.dedent("""
227 import _testcapi
228 from test import support
229
230 with support.SuppressCrashReport():
231 _testcapi.return_result_with_error()
232 """)
233 rc, out, err = assert_python_failure('-c', code)
Victor Stinner381a9bc2015-03-24 14:01:32 +0100234 self.assertRegex(err.replace(b'\r', b''),
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100235 br'Fatal Python error: _Py_CheckFunctionResult: '
236 br'a function returned a result '
237 br'with an error set\n'
Victor Stinner1ce16fb2019-09-18 01:35:33 +0200238 br'Python runtime state: initialized\n'
Victor Stinner381a9bc2015-03-24 14:01:32 +0100239 br'ValueError\n'
240 br'\n'
Serhiy Storchaka467ab192016-10-21 17:09:17 +0300241 br'The above exception was the direct cause '
242 br'of the following exception:\n'
Victor Stinner381a9bc2015-03-24 14:01:32 +0100243 br'\n'
244 br'SystemError: <built-in '
245 br'function return_result_with_error> '
246 br'returned a result with an error set\n'
247 br'\n'
248 br'Current thread.*:\n'
249 br' File .*, line 6 in <module>')
Victor Stinnerefde1462015-03-21 15:04:43 +0100250 else:
251 with self.assertRaises(SystemError) as cm:
252 _testcapi.return_result_with_error()
253 self.assertRegex(str(cm.exception),
254 'return_result_with_error.* '
255 'returned a result with an error set')
256
Serhiy Storchaka13e602e2016-05-20 22:31:14 +0300257 def test_buildvalue_N(self):
258 _testcapi.test_buildvalue_N()
259
xdegaye85f64302017-07-01 14:14:45 +0200260 def test_set_nomemory(self):
261 code = """if 1:
262 import _testcapi
263
264 class C(): pass
265
266 # The first loop tests both functions and that remove_mem_hooks()
267 # can be called twice in a row. The second loop checks a call to
268 # set_nomemory() after a call to remove_mem_hooks(). The third
269 # loop checks the start and stop arguments of set_nomemory().
270 for outer_cnt in range(1, 4):
271 start = 10 * outer_cnt
272 for j in range(100):
273 if j == 0:
274 if outer_cnt != 3:
275 _testcapi.set_nomemory(start)
276 else:
277 _testcapi.set_nomemory(start, start + 1)
278 try:
279 C()
280 except MemoryError as e:
281 if outer_cnt != 3:
282 _testcapi.remove_mem_hooks()
283 print('MemoryError', outer_cnt, j)
284 _testcapi.remove_mem_hooks()
285 break
286 """
287 rc, out, err = assert_python_ok('-c', code)
288 self.assertIn(b'MemoryError 1 10', out)
289 self.assertIn(b'MemoryError 2 20', out)
290 self.assertIn(b'MemoryError 3 30', out)
291
Oren Milman0ccc0f62017-10-08 11:17:46 +0300292 def test_mapping_keys_values_items(self):
293 class Mapping1(dict):
294 def keys(self):
295 return list(super().keys())
296 def values(self):
297 return list(super().values())
298 def items(self):
299 return list(super().items())
300 class Mapping2(dict):
301 def keys(self):
302 return tuple(super().keys())
303 def values(self):
304 return tuple(super().values())
305 def items(self):
306 return tuple(super().items())
307 dict_obj = {'foo': 1, 'bar': 2, 'spam': 3}
308
309 for mapping in [{}, OrderedDict(), Mapping1(), Mapping2(),
310 dict_obj, OrderedDict(dict_obj),
311 Mapping1(dict_obj), Mapping2(dict_obj)]:
312 self.assertListEqual(_testcapi.get_mapping_keys(mapping),
313 list(mapping.keys()))
314 self.assertListEqual(_testcapi.get_mapping_values(mapping),
315 list(mapping.values()))
316 self.assertListEqual(_testcapi.get_mapping_items(mapping),
317 list(mapping.items()))
318
319 def test_mapping_keys_values_items_bad_arg(self):
320 self.assertRaises(AttributeError, _testcapi.get_mapping_keys, None)
321 self.assertRaises(AttributeError, _testcapi.get_mapping_values, None)
322 self.assertRaises(AttributeError, _testcapi.get_mapping_items, None)
323
324 class BadMapping:
325 def keys(self):
326 return None
327 def values(self):
328 return None
329 def items(self):
330 return None
331 bad_mapping = BadMapping()
332 self.assertRaises(TypeError, _testcapi.get_mapping_keys, bad_mapping)
333 self.assertRaises(TypeError, _testcapi.get_mapping_values, bad_mapping)
334 self.assertRaises(TypeError, _testcapi.get_mapping_items, bad_mapping)
335
Victor Stinner18618e652018-10-25 17:28:11 +0200336 @unittest.skipUnless(hasattr(_testcapi, 'negative_refcount'),
337 'need _testcapi.negative_refcount')
338 def test_negative_refcount(self):
339 # bpo-35059: Check that Py_DECREF() reports the correct filename
340 # when calling _Py_NegativeRefcount() to abort Python.
341 code = textwrap.dedent("""
342 import _testcapi
343 from test import support
344
345 with support.SuppressCrashReport():
346 _testcapi.negative_refcount()
347 """)
348 rc, out, err = assert_python_failure('-c', code)
349 self.assertRegex(err,
Victor Stinner3ec9af72018-10-26 02:12:34 +0200350 br'_testcapimodule\.c:[0-9]+: '
Victor Stinnerf1d002c2018-11-21 23:53:44 +0100351 br'_Py_NegativeRefcount: Assertion failed: '
Victor Stinner3ec9af72018-10-26 02:12:34 +0200352 br'object has negative ref count')
Victor Stinner18618e652018-10-25 17:28:11 +0200353
Jeroen Demeyer351c6742019-05-10 19:21:11 +0200354 def test_trashcan_subclass(self):
355 # bpo-35983: Check that the trashcan mechanism for "list" is NOT
356 # activated when its tp_dealloc is being called by a subclass
357 from _testcapi import MyList
358 L = None
359 for i in range(1000):
360 L = MyList((L,))
361
Victor Stinner0127bb12019-11-21 12:54:02 +0100362 @support.requires_resource('cpu')
Jeroen Demeyer351c6742019-05-10 19:21:11 +0200363 def test_trashcan_python_class1(self):
364 self.do_test_trashcan_python_class(list)
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_class2(self):
368 from _testcapi import MyList
369 self.do_test_trashcan_python_class(MyList)
370
371 def do_test_trashcan_python_class(self, base):
372 # Check that the trashcan mechanism works properly for a Python
373 # subclass of a class using the trashcan (this specific test assumes
374 # that the base class "base" behaves like list)
375 class PyList(base):
376 # Count the number of PyList instances to verify that there is
377 # no memory leak
378 num = 0
379 def __init__(self, *args):
380 __class__.num += 1
381 super().__init__(*args)
382 def __del__(self):
383 __class__.num -= 1
384
385 for parity in (0, 1):
386 L = None
387 # We need in the order of 2**20 iterations here such that a
388 # typical 8MB stack would overflow without the trashcan.
389 for i in range(2**20):
390 L = PyList((L,))
391 L.attr = i
392 if parity:
393 # Add one additional nesting layer
394 L = (L,)
395 self.assertGreater(PyList.num, 0)
396 del L
397 self.assertEqual(PyList.num, 0)
398
Eddie Elizondoff023ed2019-09-11 05:17:13 -0400399 def test_subclass_of_heap_gc_ctype_with_tpdealloc_decrefs_once(self):
400 class HeapGcCTypeSubclass(_testcapi.HeapGcCType):
401 def __init__(self):
402 self.value2 = 20
403 super().__init__()
404
405 subclass_instance = HeapGcCTypeSubclass()
406 type_refcnt = sys.getrefcount(HeapGcCTypeSubclass)
407
408 # Test that subclass instance was fully created
409 self.assertEqual(subclass_instance.value, 10)
410 self.assertEqual(subclass_instance.value2, 20)
411
412 # Test that the type reference count is only decremented once
413 del subclass_instance
414 self.assertEqual(type_refcnt - 1, sys.getrefcount(HeapGcCTypeSubclass))
415
416 def test_subclass_of_heap_gc_ctype_with_del_modifying_dunder_class_only_decrefs_once(self):
417 class A(_testcapi.HeapGcCType):
418 def __init__(self):
419 self.value2 = 20
420 super().__init__()
421
422 class B(A):
423 def __init__(self):
424 super().__init__()
425
426 def __del__(self):
427 self.__class__ = A
428 A.refcnt_in_del = sys.getrefcount(A)
429 B.refcnt_in_del = sys.getrefcount(B)
430
431 subclass_instance = B()
432 type_refcnt = sys.getrefcount(B)
433 new_type_refcnt = sys.getrefcount(A)
434
435 # Test that subclass instance was fully created
436 self.assertEqual(subclass_instance.value, 10)
437 self.assertEqual(subclass_instance.value2, 20)
438
439 del subclass_instance
440
441 # Test that setting __class__ modified the reference counts of the types
442 self.assertEqual(type_refcnt - 1, B.refcnt_in_del)
443 self.assertEqual(new_type_refcnt + 1, A.refcnt_in_del)
444
445 # Test that the original type already has decreased its refcnt
446 self.assertEqual(type_refcnt - 1, sys.getrefcount(B))
447
448 # Test that subtype_dealloc decref the newly assigned __class__ only once
449 self.assertEqual(new_type_refcnt, sys.getrefcount(A))
450
Eddie Elizondo3368f3c2019-09-19 09:29:05 -0700451 def test_heaptype_with_dict(self):
452 inst = _testcapi.HeapCTypeWithDict()
453 inst.foo = 42
454 self.assertEqual(inst.foo, 42)
455 self.assertEqual(inst.dictobj, inst.__dict__)
456 self.assertEqual(inst.dictobj, {"foo": 42})
457
458 inst = _testcapi.HeapCTypeWithDict()
459 self.assertEqual({}, inst.__dict__)
460
461 def test_heaptype_with_negative_dict(self):
462 inst = _testcapi.HeapCTypeWithNegativeDict()
463 inst.foo = 42
464 self.assertEqual(inst.foo, 42)
465 self.assertEqual(inst.dictobj, inst.__dict__)
466 self.assertEqual(inst.dictobj, {"foo": 42})
467
468 inst = _testcapi.HeapCTypeWithNegativeDict()
469 self.assertEqual({}, inst.__dict__)
470
471 def test_heaptype_with_weakref(self):
472 inst = _testcapi.HeapCTypeWithWeakref()
473 ref = weakref.ref(inst)
474 self.assertEqual(ref(), inst)
475 self.assertEqual(inst.weakreflist, ref)
476
Eddie Elizondoff023ed2019-09-11 05:17:13 -0400477 def test_c_subclass_of_heap_ctype_with_tpdealloc_decrefs_once(self):
478 subclass_instance = _testcapi.HeapCTypeSubclass()
479 type_refcnt = sys.getrefcount(_testcapi.HeapCTypeSubclass)
480
481 # Test that subclass instance was fully created
482 self.assertEqual(subclass_instance.value, 10)
483 self.assertEqual(subclass_instance.value2, 20)
484
485 # Test that the type reference count is only decremented once
486 del subclass_instance
487 self.assertEqual(type_refcnt - 1, sys.getrefcount(_testcapi.HeapCTypeSubclass))
488
489 def test_c_subclass_of_heap_ctype_with_del_modifying_dunder_class_only_decrefs_once(self):
490 subclass_instance = _testcapi.HeapCTypeSubclassWithFinalizer()
491 type_refcnt = sys.getrefcount(_testcapi.HeapCTypeSubclassWithFinalizer)
492 new_type_refcnt = sys.getrefcount(_testcapi.HeapCTypeSubclass)
493
494 # Test that subclass instance was fully created
495 self.assertEqual(subclass_instance.value, 10)
496 self.assertEqual(subclass_instance.value2, 20)
497
498 # The tp_finalize slot will set __class__ to HeapCTypeSubclass
499 del subclass_instance
500
501 # Test that setting __class__ modified the reference counts of the types
502 self.assertEqual(type_refcnt - 1, _testcapi.HeapCTypeSubclassWithFinalizer.refcnt_in_del)
503 self.assertEqual(new_type_refcnt + 1, _testcapi.HeapCTypeSubclass.refcnt_in_del)
504
505 # Test that the original type already has decreased its refcnt
506 self.assertEqual(type_refcnt - 1, sys.getrefcount(_testcapi.HeapCTypeSubclassWithFinalizer))
507
508 # Test that subtype_dealloc decref the newly assigned __class__ only once
509 self.assertEqual(new_type_refcnt, sys.getrefcount(_testcapi.HeapCTypeSubclass))
510
Serhiy Storchakae5ccc942020-03-09 20:03:38 +0200511 def test_pynumber_tobase(self):
512 from _testcapi import pynumber_tobase
513 self.assertEqual(pynumber_tobase(123, 2), '0b1111011')
514 self.assertEqual(pynumber_tobase(123, 8), '0o173')
515 self.assertEqual(pynumber_tobase(123, 10), '123')
516 self.assertEqual(pynumber_tobase(123, 16), '0x7b')
517 self.assertEqual(pynumber_tobase(-123, 2), '-0b1111011')
518 self.assertEqual(pynumber_tobase(-123, 8), '-0o173')
519 self.assertEqual(pynumber_tobase(-123, 10), '-123')
520 self.assertEqual(pynumber_tobase(-123, 16), '-0x7b')
521 self.assertRaises(TypeError, pynumber_tobase, 123.0, 10)
522 self.assertRaises(TypeError, pynumber_tobase, '123', 10)
523 self.assertRaises(SystemError, pynumber_tobase, 123, 0)
524
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800525
Benjamin Petersona54c9092009-01-13 02:11:23 +0000526class TestPendingCalls(unittest.TestCase):
527
528 def pendingcalls_submit(self, l, n):
529 def callback():
530 #this function can be interrupted by thread switching so let's
531 #use an atomic operation
532 l.append(None)
533
534 for i in range(n):
535 time.sleep(random.random()*0.02) #0.01 secs on average
536 #try submitting callback until successful.
537 #rely on regular interrupt to flush queue if we are
538 #unsuccessful.
539 while True:
540 if _testcapi._pending_threadfunc(callback):
541 break;
542
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000543 def pendingcalls_wait(self, l, n, context = None):
Benjamin Petersona54c9092009-01-13 02:11:23 +0000544 #now, stick around until l[0] has grown to 10
545 count = 0;
546 while len(l) != n:
547 #this busy loop is where we expect to be interrupted to
548 #run our callbacks. Note that callbacks are only run on the
549 #main thread
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000550 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +0000551 print("(%i)"%(len(l),),)
552 for i in range(1000):
553 a = i*i
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000554 if context and not context.event.is_set():
555 continue
Benjamin Petersona54c9092009-01-13 02:11:23 +0000556 count += 1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000557 self.assertTrue(count < 10000,
Benjamin Petersona54c9092009-01-13 02:11:23 +0000558 "timeout waiting for %i callbacks, got %i"%(n, len(l)))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000559 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +0000560 print("(%i)"%(len(l),))
561
562 def test_pendingcalls_threaded(self):
Benjamin Petersona54c9092009-01-13 02:11:23 +0000563
564 #do every callback on a separate thread
Victor Stinnere225beb2019-06-03 18:14:24 +0200565 n = 32 #total callbacks
Benjamin Petersona54c9092009-01-13 02:11:23 +0000566 threads = []
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000567 class foo(object):pass
568 context = foo()
569 context.l = []
570 context.n = 2 #submits per thread
571 context.nThreads = n // context.n
572 context.nFinished = 0
573 context.lock = threading.Lock()
574 context.event = threading.Event()
575
Serhiy Storchaka263dcd22015-04-01 13:01:14 +0300576 threads = [threading.Thread(target=self.pendingcalls_thread,
577 args=(context,))
578 for i in range(context.nThreads)]
Hai Shie80697d2020-05-28 06:10:27 +0800579 with threading_helper.start_threads(threads):
Serhiy Storchaka263dcd22015-04-01 13:01:14 +0300580 self.pendingcalls_wait(context.l, n, context)
Benjamin Petersona54c9092009-01-13 02:11:23 +0000581
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000582 def pendingcalls_thread(self, context):
583 try:
584 self.pendingcalls_submit(context.l, context.n)
585 finally:
586 with context.lock:
587 context.nFinished += 1
588 nFinished = context.nFinished
589 if False and support.verbose:
590 print("finished threads: ", nFinished)
591 if nFinished == context.nThreads:
592 context.event.set()
593
Benjamin Petersona54c9092009-01-13 02:11:23 +0000594 def test_pendingcalls_non_threaded(self):
Ezio Melotti13925002011-03-16 11:05:33 +0200595 #again, just using the main thread, likely they will all be dispatched at
Benjamin Petersona54c9092009-01-13 02:11:23 +0000596 #once. It is ok to ask for too many, because we loop until we find a slot.
597 #the loop can be interrupted to dispatch.
598 #there are only 32 dispatch slots, so we go for twice that!
599 l = []
600 n = 64
601 self.pendingcalls_submit(l, n)
602 self.pendingcalls_wait(l, n)
603
Antoine Pitrou7a2572c2013-08-01 20:43:26 +0200604
605class SubinterpreterTest(unittest.TestCase):
606
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100607 def test_subinterps(self):
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100608 import builtins
609 r, w = os.pipe()
610 code = """if 1:
611 import sys, builtins, pickle
612 with open({:d}, "wb") as f:
613 pickle.dump(id(sys.modules), f)
614 pickle.dump(id(builtins), f)
615 """.format(w)
616 with open(r, "rb") as f:
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100617 ret = support.run_in_subinterp(code)
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100618 self.assertEqual(ret, 0)
619 self.assertNotEqual(pickle.load(f), id(sys.modules))
620 self.assertNotEqual(pickle.load(f), id(builtins))
621
Marcel Plch33e71e02019-05-22 13:51:26 +0200622 def test_mutate_exception(self):
623 """
624 Exceptions saved in global module state get shared between
625 individual module instances. This test checks whether or not
626 a change in one interpreter's module gets reflected into the
627 other ones.
628 """
629 import binascii
630
631 support.run_in_subinterp("import binascii; binascii.Error.foobar = 'foobar'")
632
633 self.assertFalse(hasattr(binascii.Error, "foobar"))
634
Antoine Pitrou7a2572c2013-08-01 20:43:26 +0200635
Ezio Melotti29267c82013-02-23 05:52:46 +0200636class TestThreadState(unittest.TestCase):
637
Hai Shie80697d2020-05-28 06:10:27 +0800638 @threading_helper.reap_threads
Ezio Melotti29267c82013-02-23 05:52:46 +0200639 def test_thread_state(self):
640 # some extra thread-state tests driven via _testcapi
641 def target():
642 idents = []
643
644 def callback():
Ezio Melotti35246bd2013-02-23 05:58:38 +0200645 idents.append(threading.get_ident())
Ezio Melotti29267c82013-02-23 05:52:46 +0200646
647 _testcapi._test_thread_state(callback)
648 a = b = callback
649 time.sleep(1)
650 # Check our main thread is in the list exactly 3 times.
Ezio Melotti35246bd2013-02-23 05:58:38 +0200651 self.assertEqual(idents.count(threading.get_ident()), 3,
Ezio Melotti29267c82013-02-23 05:52:46 +0200652 "Couldn't find main thread correctly in the list")
653
654 target()
655 t = threading.Thread(target=target)
656 t.start()
657 t.join()
658
Victor Stinner34be8072016-03-14 12:04:26 +0100659
Zachary Warec12f09e2013-11-11 22:47:04 -0600660class Test_testcapi(unittest.TestCase):
Serhiy Storchaka8f7bb102018-08-06 16:50:19 +0300661 locals().update((name, getattr(_testcapi, name))
662 for name in dir(_testcapi)
663 if name.startswith('test_') and not name.endswith('_code'))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000664
Victor Stinner34be8072016-03-14 12:04:26 +0100665
Victor Stinner1ae035b2020-04-17 17:47:20 +0200666class Test_testinternalcapi(unittest.TestCase):
667 locals().update((name, getattr(_testinternalcapi, name))
668 for name in dir(_testinternalcapi)
669 if name.startswith('test_'))
670
671
Victor Stinnerc4aec362016-03-14 22:26:53 +0100672class PyMemDebugTests(unittest.TestCase):
673 PYTHONMALLOC = 'debug'
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100674 # '0x04c06e0' or '04C06E0'
Victor Stinner08572f62016-03-14 21:55:43 +0100675 PTR_REGEX = r'(?:0x)?[0-9a-fA-F]+'
Victor Stinner34be8072016-03-14 12:04:26 +0100676
677 def check(self, code):
678 with support.SuppressCrashReport():
Victor Stinnerc4aec362016-03-14 22:26:53 +0100679 out = assert_python_failure('-c', code,
680 PYTHONMALLOC=self.PYTHONMALLOC)
Victor Stinner34be8072016-03-14 12:04:26 +0100681 stderr = out.err
682 return stderr.decode('ascii', 'replace')
683
684 def test_buffer_overflow(self):
685 out = self.check('import _testcapi; _testcapi.pymem_buffer_overflow()')
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100686 regex = (r"Debug memory block at address p={ptr}: API 'm'\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100687 r" 16 bytes originally requested\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100688 r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n"
689 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 +0100690 r" at tail\+0: 0x78 \*\*\* OUCH\n"
Victor Stinner4c409be2019-04-11 13:01:15 +0200691 r" at tail\+1: 0xfd\n"
692 r" at tail\+2: 0xfd\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100693 r" .*\n"
Victor Stinnere8f9acf2019-04-12 21:54:06 +0200694 r"( The block was made by call #[0-9]+ to debug malloc/realloc.\n)?"
Victor Stinner4c409be2019-04-11 13:01:15 +0200695 r" Data at p: cd cd cd .*\n"
Victor Stinner6453e9e2016-03-15 23:36:28 +0100696 r"\n"
Victor Stinnerf966e532018-11-13 15:14:58 +0100697 r"Enable tracemalloc to get the memory block allocation traceback\n"
698 r"\n"
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100699 r"Fatal Python error: _PyMem_DebugRawFree: bad trailing pad byte")
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100700 regex = regex.format(ptr=self.PTR_REGEX)
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100701 regex = re.compile(regex, flags=re.DOTALL)
Victor Stinner34be8072016-03-14 12:04:26 +0100702 self.assertRegex(out, regex)
703
704 def test_api_misuse(self):
705 out = self.check('import _testcapi; _testcapi.pymem_api_misuse()')
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100706 regex = (r"Debug memory block at address p={ptr}: API 'm'\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100707 r" 16 bytes originally requested\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100708 r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n"
709 r" The [0-9] pad bytes at tail={ptr} are FORBIDDENBYTE, as expected.\n"
Victor Stinnere8f9acf2019-04-12 21:54:06 +0200710 r"( The block was made by call #[0-9]+ to debug malloc/realloc.\n)?"
Victor Stinner4c409be2019-04-11 13:01:15 +0200711 r" Data at p: cd cd cd .*\n"
Victor Stinner6453e9e2016-03-15 23:36:28 +0100712 r"\n"
Victor Stinnerf966e532018-11-13 15:14:58 +0100713 r"Enable tracemalloc to get the memory block allocation traceback\n"
714 r"\n"
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100715 r"Fatal Python error: _PyMem_DebugRawFree: bad ID: Allocated using API 'm', verified using API 'r'\n")
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100716 regex = regex.format(ptr=self.PTR_REGEX)
Victor Stinner34be8072016-03-14 12:04:26 +0100717 self.assertRegex(out, regex)
718
Victor Stinnerad524372016-03-16 12:12:53 +0100719 def check_malloc_without_gil(self, code):
Victor Stinnerc4aec362016-03-14 22:26:53 +0100720 out = self.check(code)
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100721 expected = ('Fatal Python error: _PyMem_DebugMalloc: '
722 'Python memory allocator called without holding the GIL')
Victor Stinnerc4aec362016-03-14 22:26:53 +0100723 self.assertIn(expected, out)
Victor Stinner34be8072016-03-14 12:04:26 +0100724
Victor Stinnerad524372016-03-16 12:12:53 +0100725 def test_pymem_malloc_without_gil(self):
726 # Debug hooks must raise an error if PyMem_Malloc() is called
727 # without holding the GIL
728 code = 'import _testcapi; _testcapi.pymem_malloc_without_gil()'
729 self.check_malloc_without_gil(code)
730
731 def test_pyobject_malloc_without_gil(self):
732 # Debug hooks must raise an error if PyObject_Malloc() is called
733 # without holding the GIL
734 code = 'import _testcapi; _testcapi.pyobject_malloc_without_gil()'
735 self.check_malloc_without_gil(code)
736
Victor Stinner3bf0f3a2019-06-07 16:22:21 +0200737 def check_pyobject_is_freed(self, func_name):
738 code = textwrap.dedent(f'''
Victor Stinner2b00db62019-04-11 11:33:27 +0200739 import gc, os, sys, _testcapi
740 # Disable the GC to avoid crash on GC collection
741 gc.disable()
Victor Stinner3bf0f3a2019-06-07 16:22:21 +0200742 try:
743 _testcapi.{func_name}()
744 # Exit immediately to avoid a crash while deallocating
745 # the invalid object
746 os._exit(0)
747 except _testcapi.error:
748 os._exit(1)
Victor Stinner2b00db62019-04-11 11:33:27 +0200749 ''')
Victor Stinner2b00db62019-04-11 11:33:27 +0200750 assert_python_ok('-c', code, PYTHONMALLOC=self.PYTHONMALLOC)
751
Victor Stinner68762572019-10-07 18:42:01 +0200752 def test_pyobject_null_is_freed(self):
753 self.check_pyobject_is_freed('check_pyobject_null_is_freed')
754
Victor Stinner3bf0f3a2019-06-07 16:22:21 +0200755 def test_pyobject_uninitialized_is_freed(self):
756 self.check_pyobject_is_freed('check_pyobject_uninitialized_is_freed')
Victor Stinner2b00db62019-04-11 11:33:27 +0200757
Victor Stinner3bf0f3a2019-06-07 16:22:21 +0200758 def test_pyobject_forbidden_bytes_is_freed(self):
759 self.check_pyobject_is_freed('check_pyobject_forbidden_bytes_is_freed')
Victor Stinner2b00db62019-04-11 11:33:27 +0200760
Victor Stinner3bf0f3a2019-06-07 16:22:21 +0200761 def test_pyobject_freed_is_freed(self):
762 self.check_pyobject_is_freed('check_pyobject_freed_is_freed')
Victor Stinner2b00db62019-04-11 11:33:27 +0200763
Victor Stinnerc4aec362016-03-14 22:26:53 +0100764
765class PyMemMallocDebugTests(PyMemDebugTests):
766 PYTHONMALLOC = 'malloc_debug'
Victor Stinner34be8072016-03-14 12:04:26 +0100767
768
Victor Stinner5d39e042017-11-29 17:20:38 +0100769@unittest.skipUnless(support.with_pymalloc(), 'need pymalloc')
Victor Stinnerc4aec362016-03-14 22:26:53 +0100770class PyMemPymallocDebugTests(PyMemDebugTests):
771 PYTHONMALLOC = 'pymalloc_debug'
Victor Stinner34be8072016-03-14 12:04:26 +0100772
773
774@unittest.skipUnless(Py_DEBUG, 'need Py_DEBUG')
Victor Stinnerc4aec362016-03-14 22:26:53 +0100775class PyMemDefaultTests(PyMemDebugTests):
776 # test default allocator of Python compiled in debug mode
777 PYTHONMALLOC = ''
Victor Stinner34be8072016-03-14 12:04:26 +0100778
779
Petr Viktorine1becf42020-05-07 15:39:59 +0200780class Test_ModuleStateAccess(unittest.TestCase):
781 """Test access to module start (PEP 573)"""
782
783 # The C part of the tests lives in _testmultiphase, in a module called
784 # _testmultiphase_meth_state_access.
785 # This module has multi-phase initialization, unlike _testcapi.
786
787 def setUp(self):
788 fullname = '_testmultiphase_meth_state_access' # XXX
789 origin = importlib.util.find_spec('_testmultiphase').origin
790 loader = importlib.machinery.ExtensionFileLoader(fullname, origin)
791 spec = importlib.util.spec_from_loader(fullname, loader)
792 module = importlib.util.module_from_spec(spec)
793 loader.exec_module(module)
794 self.module = module
795
796 def test_subclass_get_module(self):
797 """PyType_GetModule for defining_class"""
798 class StateAccessType_Subclass(self.module.StateAccessType):
799 pass
800
801 instance = StateAccessType_Subclass()
802 self.assertIs(instance.get_defining_module(), self.module)
803
804 def test_subclass_get_module_with_super(self):
805 class StateAccessType_Subclass(self.module.StateAccessType):
806 def get_defining_module(self):
807 return super().get_defining_module()
808
809 instance = StateAccessType_Subclass()
810 self.assertIs(instance.get_defining_module(), self.module)
811
812 def test_state_access(self):
813 """Checks methods defined with and without argument clinic
814
815 This tests a no-arg method (get_count) and a method with
816 both a positional and keyword argument.
817 """
818
819 a = self.module.StateAccessType()
820 b = self.module.StateAccessType()
821
822 methods = {
823 'clinic': a.increment_count_clinic,
824 'noclinic': a.increment_count_noclinic,
825 }
826
827 for name, increment_count in methods.items():
828 with self.subTest(name):
829 self.assertEqual(a.get_count(), b.get_count())
830 self.assertEqual(a.get_count(), 0)
831
832 increment_count()
833 self.assertEqual(a.get_count(), b.get_count())
834 self.assertEqual(a.get_count(), 1)
835
836 increment_count(3)
837 self.assertEqual(a.get_count(), b.get_count())
838 self.assertEqual(a.get_count(), 4)
839
840 increment_count(-2, twice=True)
841 self.assertEqual(a.get_count(), b.get_count())
842 self.assertEqual(a.get_count(), 0)
843
844 with self.assertRaises(TypeError):
845 increment_count(thrice=3)
846
847 with self.assertRaises(TypeError):
848 increment_count(1, 2, 3)
849
850
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000851if __name__ == "__main__":
Zachary Warec12f09e2013-11-11 22:47:04 -0600852 unittest.main()