blob: 5c7526aa7ec29a64b83d69cfe411c6ac5f21831c [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
xdegaye85f64302017-07-01 14:14:45 +020020from test.support.script_helper import assert_python_failure, assert_python_ok
Victor Stinner45df8202010-04-28 22:31:17 +000021try:
Stefan Krahfd24f9e2012-08-20 11:04:24 +020022 import _posixsubprocess
23except ImportError:
24 _posixsubprocess = None
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020025
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +020026# Skip this test if the _testcapi module isn't available.
27_testcapi = support.import_module('_testcapi')
Tim Peters9ea17ac2001-02-02 05:57:15 +000028
Victor Stinner1ae035b2020-04-17 17:47:20 +020029import _testinternalcapi
30
Victor Stinnerefde1462015-03-21 15:04:43 +010031# Were we compiled --with-pydebug or with #define Py_DEBUG?
32Py_DEBUG = hasattr(sys, 'gettotalrefcount')
33
Benjamin Petersona54c9092009-01-13 02:11:23 +000034
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000035def testfunction(self):
36 """some doc"""
37 return self
38
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +020039
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000040class InstanceMethod:
41 id = _testcapi.instancemethod(id)
42 testfunction = _testcapi.instancemethod(testfunction)
43
44class CAPITest(unittest.TestCase):
45
46 def test_instancemethod(self):
47 inst = InstanceMethod()
48 self.assertEqual(id(inst), inst.id())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000049 self.assertTrue(inst.testfunction() is inst)
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000050 self.assertEqual(inst.testfunction.__doc__, testfunction.__doc__)
51 self.assertEqual(InstanceMethod.testfunction.__doc__, testfunction.__doc__)
52
53 InstanceMethod.testfunction.attribute = "test"
54 self.assertEqual(testfunction.attribute, "test")
55 self.assertRaises(AttributeError, setattr, inst.testfunction, "attribute", "test")
56
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000057 def test_no_FatalError_infinite_loop(self):
Antoine Pitrou77e904e2013-10-08 23:04:32 +020058 with support.SuppressCrashReport():
Ezio Melotti25a40452013-03-05 20:26:17 +020059 p = subprocess.Popen([sys.executable, "-c",
Ezio Melottie1857d92013-03-05 20:31:34 +020060 'import _testcapi;'
61 '_testcapi.crash_no_current_thread()'],
62 stdout=subprocess.PIPE,
63 stderr=subprocess.PIPE)
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000064 (out, err) = p.communicate()
65 self.assertEqual(out, b'')
66 # This used to cause an infinite loop.
Vinay Sajip73954042012-05-06 11:34:50 +010067 self.assertTrue(err.rstrip().startswith(
Victor Stinner9e5d30c2020-03-07 00:54:20 +010068 b'Fatal Python error: '
Victor Stinner23ef89d2020-03-18 02:26:04 +010069 b'PyThreadState_Get: '
70 b'current thread state is NULL (released GIL?)'))
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000071
Antoine Pitrou915605c2011-02-24 20:53:48 +000072 def test_memoryview_from_NULL_pointer(self):
73 self.assertRaises(ValueError, _testcapi.make_memoryview_from_NULL_pointer)
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000074
Martin v. Löwisaa2efcb2012-04-19 14:33:43 +020075 def test_exc_info(self):
76 raised_exception = ValueError("5")
77 new_exc = TypeError("TEST")
78 try:
79 raise raised_exception
80 except ValueError as e:
81 tb = e.__traceback__
82 orig_sys_exc_info = sys.exc_info()
83 orig_exc_info = _testcapi.set_exc_info(new_exc.__class__, new_exc, None)
84 new_sys_exc_info = sys.exc_info()
85 new_exc_info = _testcapi.set_exc_info(*orig_exc_info)
86 reset_sys_exc_info = sys.exc_info()
87
88 self.assertEqual(orig_exc_info[1], e)
89
90 self.assertSequenceEqual(orig_exc_info, (raised_exception.__class__, raised_exception, tb))
91 self.assertSequenceEqual(orig_sys_exc_info, orig_exc_info)
92 self.assertSequenceEqual(reset_sys_exc_info, orig_exc_info)
93 self.assertSequenceEqual(new_exc_info, (new_exc.__class__, new_exc, None))
94 self.assertSequenceEqual(new_sys_exc_info, new_exc_info)
95 else:
96 self.assertTrue(False)
97
Stefan Krahfd24f9e2012-08-20 11:04:24 +020098 @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
99 def test_seq_bytes_to_charp_array(self):
100 # Issue #15732: crash in _PySequence_BytesToCharpArray()
101 class Z(object):
102 def __len__(self):
103 return 1
104 self.assertRaises(TypeError, _posixsubprocess.fork_exec,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -0700105 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 +0200106 # Issue #15736: overflow in _PySequence_BytesToCharpArray()
107 class Z(object):
108 def __len__(self):
109 return sys.maxsize
110 def __getitem__(self, i):
111 return b'x'
112 self.assertRaises(MemoryError, _posixsubprocess.fork_exec,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -0700113 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 +0200114
Stefan Krahdb579d72012-08-20 14:36:47 +0200115 @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
116 def test_subprocess_fork_exec(self):
117 class Z(object):
118 def __len__(self):
119 return 1
120
121 # Issue #15738: crash in subprocess_fork_exec()
122 self.assertRaises(TypeError, _posixsubprocess.fork_exec,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -0700123 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 +0200124
Larry Hastingsfcafe432013-11-23 17:35:48 -0800125 @unittest.skipIf(MISSING_C_DOCSTRINGS,
126 "Signature information for builtins requires docstrings")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800127 def test_docstring_signature_parsing(self):
128
129 self.assertEqual(_testcapi.no_docstring.__doc__, None)
130 self.assertEqual(_testcapi.no_docstring.__text_signature__, None)
131
Zachary Ware8ef887c2015-04-13 18:22:35 -0500132 self.assertEqual(_testcapi.docstring_empty.__doc__, None)
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800133 self.assertEqual(_testcapi.docstring_empty.__text_signature__, None)
134
135 self.assertEqual(_testcapi.docstring_no_signature.__doc__,
136 "This docstring has no signature.")
137 self.assertEqual(_testcapi.docstring_no_signature.__text_signature__, None)
138
139 self.assertEqual(_testcapi.docstring_with_invalid_signature.__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800140 "docstring_with_invalid_signature($module, /, boo)\n"
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800141 "\n"
142 "This docstring has an invalid signature."
143 )
144 self.assertEqual(_testcapi.docstring_with_invalid_signature.__text_signature__, None)
145
Larry Hastings2623c8c2014-02-08 22:15:29 -0800146 self.assertEqual(_testcapi.docstring_with_invalid_signature2.__doc__,
147 "docstring_with_invalid_signature2($module, /, boo)\n"
148 "\n"
149 "--\n"
150 "\n"
151 "This docstring also has an invalid signature."
152 )
153 self.assertEqual(_testcapi.docstring_with_invalid_signature2.__text_signature__, None)
154
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800155 self.assertEqual(_testcapi.docstring_with_signature.__doc__,
156 "This docstring has a valid signature.")
Larry Hastings2623c8c2014-02-08 22:15:29 -0800157 self.assertEqual(_testcapi.docstring_with_signature.__text_signature__, "($module, /, sig)")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800158
Zachary Ware8ef887c2015-04-13 18:22:35 -0500159 self.assertEqual(_testcapi.docstring_with_signature_but_no_doc.__doc__, None)
160 self.assertEqual(_testcapi.docstring_with_signature_but_no_doc.__text_signature__,
161 "($module, /, sig)")
162
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800163 self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800164 "\nThis docstring has a valid signature and some extra newlines.")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800165 self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__text_signature__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800166 "($module, /, parameter)")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800167
Benjamin Petersond51374e2014-04-09 23:55:56 -0400168 def test_c_type_with_matrix_multiplication(self):
169 M = _testcapi.matmulType
170 m1 = M()
171 m2 = M()
172 self.assertEqual(m1 @ m2, ("matmul", m1, m2))
173 self.assertEqual(m1 @ 42, ("matmul", m1, 42))
174 self.assertEqual(42 @ m1, ("matmul", 42, m1))
175 o = m1
176 o @= m2
177 self.assertEqual(o, ("imatmul", m1, m2))
178 o = m1
179 o @= 42
180 self.assertEqual(o, ("imatmul", m1, 42))
181 o = 42
182 o @= m1
183 self.assertEqual(o, ("matmul", 42, m1))
184
Zackery Spytzc7f803b2019-05-31 03:46:36 -0600185 def test_c_type_with_ipow(self):
186 # When the __ipow__ method of a type was implemented in C, using the
187 # modulo param would cause segfaults.
188 o = _testcapi.ipowType()
189 self.assertEqual(o.__ipow__(1), (1, None))
190 self.assertEqual(o.__ipow__(2, 2), (2, 2))
191
Victor Stinnerefde1462015-03-21 15:04:43 +0100192 def test_return_null_without_error(self):
193 # Issue #23571: A function must not return NULL without setting an
194 # error
195 if Py_DEBUG:
196 code = textwrap.dedent("""
197 import _testcapi
198 from test import support
199
200 with support.SuppressCrashReport():
201 _testcapi.return_null_without_error()
202 """)
203 rc, out, err = assert_python_failure('-c', code)
Victor Stinner381a9bc2015-03-24 14:01:32 +0100204 self.assertRegex(err.replace(b'\r', b''),
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100205 br'Fatal Python error: _Py_CheckFunctionResult: '
206 br'a function returned NULL '
Victor Stinner944fbcc2015-03-24 16:28:52 +0100207 br'without setting an error\n'
Victor Stinner1ce16fb2019-09-18 01:35:33 +0200208 br'Python runtime state: initialized\n'
Victor Stinner381a9bc2015-03-24 14:01:32 +0100209 br'SystemError: <built-in function '
210 br'return_null_without_error> returned NULL '
211 br'without setting an error\n'
212 br'\n'
213 br'Current thread.*:\n'
214 br' File .*", line 6 in <module>')
Victor Stinnerefde1462015-03-21 15:04:43 +0100215 else:
216 with self.assertRaises(SystemError) as cm:
217 _testcapi.return_null_without_error()
218 self.assertRegex(str(cm.exception),
219 'return_null_without_error.* '
220 'returned NULL without setting an error')
221
222 def test_return_result_with_error(self):
223 # Issue #23571: A function must not return a result with an error set
224 if Py_DEBUG:
225 code = textwrap.dedent("""
226 import _testcapi
227 from test import support
228
229 with support.SuppressCrashReport():
230 _testcapi.return_result_with_error()
231 """)
232 rc, out, err = assert_python_failure('-c', code)
Victor Stinner381a9bc2015-03-24 14:01:32 +0100233 self.assertRegex(err.replace(b'\r', b''),
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100234 br'Fatal Python error: _Py_CheckFunctionResult: '
235 br'a function returned a result '
236 br'with an error set\n'
Victor Stinner1ce16fb2019-09-18 01:35:33 +0200237 br'Python runtime state: initialized\n'
Victor Stinner381a9bc2015-03-24 14:01:32 +0100238 br'ValueError\n'
239 br'\n'
Serhiy Storchaka467ab192016-10-21 17:09:17 +0300240 br'The above exception was the direct cause '
241 br'of the following exception:\n'
Victor Stinner381a9bc2015-03-24 14:01:32 +0100242 br'\n'
243 br'SystemError: <built-in '
244 br'function return_result_with_error> '
245 br'returned a result with an error set\n'
246 br'\n'
247 br'Current thread.*:\n'
248 br' File .*, line 6 in <module>')
Victor Stinnerefde1462015-03-21 15:04:43 +0100249 else:
250 with self.assertRaises(SystemError) as cm:
251 _testcapi.return_result_with_error()
252 self.assertRegex(str(cm.exception),
253 'return_result_with_error.* '
254 'returned a result with an error set')
255
Serhiy Storchaka13e602e2016-05-20 22:31:14 +0300256 def test_buildvalue_N(self):
257 _testcapi.test_buildvalue_N()
258
xdegaye85f64302017-07-01 14:14:45 +0200259 def test_set_nomemory(self):
260 code = """if 1:
261 import _testcapi
262
263 class C(): pass
264
265 # The first loop tests both functions and that remove_mem_hooks()
266 # can be called twice in a row. The second loop checks a call to
267 # set_nomemory() after a call to remove_mem_hooks(). The third
268 # loop checks the start and stop arguments of set_nomemory().
269 for outer_cnt in range(1, 4):
270 start = 10 * outer_cnt
271 for j in range(100):
272 if j == 0:
273 if outer_cnt != 3:
274 _testcapi.set_nomemory(start)
275 else:
276 _testcapi.set_nomemory(start, start + 1)
277 try:
278 C()
279 except MemoryError as e:
280 if outer_cnt != 3:
281 _testcapi.remove_mem_hooks()
282 print('MemoryError', outer_cnt, j)
283 _testcapi.remove_mem_hooks()
284 break
285 """
286 rc, out, err = assert_python_ok('-c', code)
287 self.assertIn(b'MemoryError 1 10', out)
288 self.assertIn(b'MemoryError 2 20', out)
289 self.assertIn(b'MemoryError 3 30', out)
290
Oren Milman0ccc0f62017-10-08 11:17:46 +0300291 def test_mapping_keys_values_items(self):
292 class Mapping1(dict):
293 def keys(self):
294 return list(super().keys())
295 def values(self):
296 return list(super().values())
297 def items(self):
298 return list(super().items())
299 class Mapping2(dict):
300 def keys(self):
301 return tuple(super().keys())
302 def values(self):
303 return tuple(super().values())
304 def items(self):
305 return tuple(super().items())
306 dict_obj = {'foo': 1, 'bar': 2, 'spam': 3}
307
308 for mapping in [{}, OrderedDict(), Mapping1(), Mapping2(),
309 dict_obj, OrderedDict(dict_obj),
310 Mapping1(dict_obj), Mapping2(dict_obj)]:
311 self.assertListEqual(_testcapi.get_mapping_keys(mapping),
312 list(mapping.keys()))
313 self.assertListEqual(_testcapi.get_mapping_values(mapping),
314 list(mapping.values()))
315 self.assertListEqual(_testcapi.get_mapping_items(mapping),
316 list(mapping.items()))
317
318 def test_mapping_keys_values_items_bad_arg(self):
319 self.assertRaises(AttributeError, _testcapi.get_mapping_keys, None)
320 self.assertRaises(AttributeError, _testcapi.get_mapping_values, None)
321 self.assertRaises(AttributeError, _testcapi.get_mapping_items, None)
322
323 class BadMapping:
324 def keys(self):
325 return None
326 def values(self):
327 return None
328 def items(self):
329 return None
330 bad_mapping = BadMapping()
331 self.assertRaises(TypeError, _testcapi.get_mapping_keys, bad_mapping)
332 self.assertRaises(TypeError, _testcapi.get_mapping_values, bad_mapping)
333 self.assertRaises(TypeError, _testcapi.get_mapping_items, bad_mapping)
334
Victor Stinner18618e652018-10-25 17:28:11 +0200335 @unittest.skipUnless(hasattr(_testcapi, 'negative_refcount'),
336 'need _testcapi.negative_refcount')
337 def test_negative_refcount(self):
338 # bpo-35059: Check that Py_DECREF() reports the correct filename
339 # when calling _Py_NegativeRefcount() to abort Python.
340 code = textwrap.dedent("""
341 import _testcapi
342 from test import support
343
344 with support.SuppressCrashReport():
345 _testcapi.negative_refcount()
346 """)
347 rc, out, err = assert_python_failure('-c', code)
348 self.assertRegex(err,
Victor Stinner3ec9af72018-10-26 02:12:34 +0200349 br'_testcapimodule\.c:[0-9]+: '
Victor Stinnerf1d002c2018-11-21 23:53:44 +0100350 br'_Py_NegativeRefcount: Assertion failed: '
Victor Stinner3ec9af72018-10-26 02:12:34 +0200351 br'object has negative ref count')
Victor Stinner18618e652018-10-25 17:28:11 +0200352
Jeroen Demeyer351c6742019-05-10 19:21:11 +0200353 def test_trashcan_subclass(self):
354 # bpo-35983: Check that the trashcan mechanism for "list" is NOT
355 # activated when its tp_dealloc is being called by a subclass
356 from _testcapi import MyList
357 L = None
358 for i in range(1000):
359 L = MyList((L,))
360
Victor Stinner0127bb12019-11-21 12:54:02 +0100361 @support.requires_resource('cpu')
Jeroen Demeyer351c6742019-05-10 19:21:11 +0200362 def test_trashcan_python_class1(self):
363 self.do_test_trashcan_python_class(list)
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_class2(self):
367 from _testcapi import MyList
368 self.do_test_trashcan_python_class(MyList)
369
370 def do_test_trashcan_python_class(self, base):
371 # Check that the trashcan mechanism works properly for a Python
372 # subclass of a class using the trashcan (this specific test assumes
373 # that the base class "base" behaves like list)
374 class PyList(base):
375 # Count the number of PyList instances to verify that there is
376 # no memory leak
377 num = 0
378 def __init__(self, *args):
379 __class__.num += 1
380 super().__init__(*args)
381 def __del__(self):
382 __class__.num -= 1
383
384 for parity in (0, 1):
385 L = None
386 # We need in the order of 2**20 iterations here such that a
387 # typical 8MB stack would overflow without the trashcan.
388 for i in range(2**20):
389 L = PyList((L,))
390 L.attr = i
391 if parity:
392 # Add one additional nesting layer
393 L = (L,)
394 self.assertGreater(PyList.num, 0)
395 del L
396 self.assertEqual(PyList.num, 0)
397
Eddie Elizondoff023ed2019-09-11 05:17:13 -0400398 def test_subclass_of_heap_gc_ctype_with_tpdealloc_decrefs_once(self):
399 class HeapGcCTypeSubclass(_testcapi.HeapGcCType):
400 def __init__(self):
401 self.value2 = 20
402 super().__init__()
403
404 subclass_instance = HeapGcCTypeSubclass()
405 type_refcnt = sys.getrefcount(HeapGcCTypeSubclass)
406
407 # Test that subclass instance was fully created
408 self.assertEqual(subclass_instance.value, 10)
409 self.assertEqual(subclass_instance.value2, 20)
410
411 # Test that the type reference count is only decremented once
412 del subclass_instance
413 self.assertEqual(type_refcnt - 1, sys.getrefcount(HeapGcCTypeSubclass))
414
415 def test_subclass_of_heap_gc_ctype_with_del_modifying_dunder_class_only_decrefs_once(self):
416 class A(_testcapi.HeapGcCType):
417 def __init__(self):
418 self.value2 = 20
419 super().__init__()
420
421 class B(A):
422 def __init__(self):
423 super().__init__()
424
425 def __del__(self):
426 self.__class__ = A
427 A.refcnt_in_del = sys.getrefcount(A)
428 B.refcnt_in_del = sys.getrefcount(B)
429
430 subclass_instance = B()
431 type_refcnt = sys.getrefcount(B)
432 new_type_refcnt = sys.getrefcount(A)
433
434 # Test that subclass instance was fully created
435 self.assertEqual(subclass_instance.value, 10)
436 self.assertEqual(subclass_instance.value2, 20)
437
438 del subclass_instance
439
440 # Test that setting __class__ modified the reference counts of the types
441 self.assertEqual(type_refcnt - 1, B.refcnt_in_del)
442 self.assertEqual(new_type_refcnt + 1, A.refcnt_in_del)
443
444 # Test that the original type already has decreased its refcnt
445 self.assertEqual(type_refcnt - 1, sys.getrefcount(B))
446
447 # Test that subtype_dealloc decref the newly assigned __class__ only once
448 self.assertEqual(new_type_refcnt, sys.getrefcount(A))
449
Eddie Elizondo3368f3c2019-09-19 09:29:05 -0700450 def test_heaptype_with_dict(self):
451 inst = _testcapi.HeapCTypeWithDict()
452 inst.foo = 42
453 self.assertEqual(inst.foo, 42)
454 self.assertEqual(inst.dictobj, inst.__dict__)
455 self.assertEqual(inst.dictobj, {"foo": 42})
456
457 inst = _testcapi.HeapCTypeWithDict()
458 self.assertEqual({}, inst.__dict__)
459
460 def test_heaptype_with_negative_dict(self):
461 inst = _testcapi.HeapCTypeWithNegativeDict()
462 inst.foo = 42
463 self.assertEqual(inst.foo, 42)
464 self.assertEqual(inst.dictobj, inst.__dict__)
465 self.assertEqual(inst.dictobj, {"foo": 42})
466
467 inst = _testcapi.HeapCTypeWithNegativeDict()
468 self.assertEqual({}, inst.__dict__)
469
470 def test_heaptype_with_weakref(self):
471 inst = _testcapi.HeapCTypeWithWeakref()
472 ref = weakref.ref(inst)
473 self.assertEqual(ref(), inst)
474 self.assertEqual(inst.weakreflist, ref)
475
Eddie Elizondoff023ed2019-09-11 05:17:13 -0400476 def test_c_subclass_of_heap_ctype_with_tpdealloc_decrefs_once(self):
477 subclass_instance = _testcapi.HeapCTypeSubclass()
478 type_refcnt = sys.getrefcount(_testcapi.HeapCTypeSubclass)
479
480 # Test that subclass instance was fully created
481 self.assertEqual(subclass_instance.value, 10)
482 self.assertEqual(subclass_instance.value2, 20)
483
484 # Test that the type reference count is only decremented once
485 del subclass_instance
486 self.assertEqual(type_refcnt - 1, sys.getrefcount(_testcapi.HeapCTypeSubclass))
487
488 def test_c_subclass_of_heap_ctype_with_del_modifying_dunder_class_only_decrefs_once(self):
489 subclass_instance = _testcapi.HeapCTypeSubclassWithFinalizer()
490 type_refcnt = sys.getrefcount(_testcapi.HeapCTypeSubclassWithFinalizer)
491 new_type_refcnt = sys.getrefcount(_testcapi.HeapCTypeSubclass)
492
493 # Test that subclass instance was fully created
494 self.assertEqual(subclass_instance.value, 10)
495 self.assertEqual(subclass_instance.value2, 20)
496
497 # The tp_finalize slot will set __class__ to HeapCTypeSubclass
498 del subclass_instance
499
500 # Test that setting __class__ modified the reference counts of the types
501 self.assertEqual(type_refcnt - 1, _testcapi.HeapCTypeSubclassWithFinalizer.refcnt_in_del)
502 self.assertEqual(new_type_refcnt + 1, _testcapi.HeapCTypeSubclass.refcnt_in_del)
503
504 # Test that the original type already has decreased its refcnt
505 self.assertEqual(type_refcnt - 1, sys.getrefcount(_testcapi.HeapCTypeSubclassWithFinalizer))
506
507 # Test that subtype_dealloc decref the newly assigned __class__ only once
508 self.assertEqual(new_type_refcnt, sys.getrefcount(_testcapi.HeapCTypeSubclass))
509
Serhiy Storchakae5ccc942020-03-09 20:03:38 +0200510 def test_pynumber_tobase(self):
511 from _testcapi import pynumber_tobase
512 self.assertEqual(pynumber_tobase(123, 2), '0b1111011')
513 self.assertEqual(pynumber_tobase(123, 8), '0o173')
514 self.assertEqual(pynumber_tobase(123, 10), '123')
515 self.assertEqual(pynumber_tobase(123, 16), '0x7b')
516 self.assertEqual(pynumber_tobase(-123, 2), '-0b1111011')
517 self.assertEqual(pynumber_tobase(-123, 8), '-0o173')
518 self.assertEqual(pynumber_tobase(-123, 10), '-123')
519 self.assertEqual(pynumber_tobase(-123, 16), '-0x7b')
520 self.assertRaises(TypeError, pynumber_tobase, 123.0, 10)
521 self.assertRaises(TypeError, pynumber_tobase, '123', 10)
522 self.assertRaises(SystemError, pynumber_tobase, 123, 0)
523
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800524
Benjamin Petersona54c9092009-01-13 02:11:23 +0000525class TestPendingCalls(unittest.TestCase):
526
527 def pendingcalls_submit(self, l, n):
528 def callback():
529 #this function can be interrupted by thread switching so let's
530 #use an atomic operation
531 l.append(None)
532
533 for i in range(n):
534 time.sleep(random.random()*0.02) #0.01 secs on average
535 #try submitting callback until successful.
536 #rely on regular interrupt to flush queue if we are
537 #unsuccessful.
538 while True:
539 if _testcapi._pending_threadfunc(callback):
540 break;
541
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000542 def pendingcalls_wait(self, l, n, context = None):
Benjamin Petersona54c9092009-01-13 02:11:23 +0000543 #now, stick around until l[0] has grown to 10
544 count = 0;
545 while len(l) != n:
546 #this busy loop is where we expect to be interrupted to
547 #run our callbacks. Note that callbacks are only run on the
548 #main thread
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000549 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +0000550 print("(%i)"%(len(l),),)
551 for i in range(1000):
552 a = i*i
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000553 if context and not context.event.is_set():
554 continue
Benjamin Petersona54c9092009-01-13 02:11:23 +0000555 count += 1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000556 self.assertTrue(count < 10000,
Benjamin Petersona54c9092009-01-13 02:11:23 +0000557 "timeout waiting for %i callbacks, got %i"%(n, len(l)))
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
561 def test_pendingcalls_threaded(self):
Benjamin Petersona54c9092009-01-13 02:11:23 +0000562
563 #do every callback on a separate thread
Victor Stinnere225beb2019-06-03 18:14:24 +0200564 n = 32 #total callbacks
Benjamin Petersona54c9092009-01-13 02:11:23 +0000565 threads = []
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000566 class foo(object):pass
567 context = foo()
568 context.l = []
569 context.n = 2 #submits per thread
570 context.nThreads = n // context.n
571 context.nFinished = 0
572 context.lock = threading.Lock()
573 context.event = threading.Event()
574
Serhiy Storchaka263dcd22015-04-01 13:01:14 +0300575 threads = [threading.Thread(target=self.pendingcalls_thread,
576 args=(context,))
577 for i in range(context.nThreads)]
578 with support.start_threads(threads):
579 self.pendingcalls_wait(context.l, n, context)
Benjamin Petersona54c9092009-01-13 02:11:23 +0000580
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000581 def pendingcalls_thread(self, context):
582 try:
583 self.pendingcalls_submit(context.l, context.n)
584 finally:
585 with context.lock:
586 context.nFinished += 1
587 nFinished = context.nFinished
588 if False and support.verbose:
589 print("finished threads: ", nFinished)
590 if nFinished == context.nThreads:
591 context.event.set()
592
Benjamin Petersona54c9092009-01-13 02:11:23 +0000593 def test_pendingcalls_non_threaded(self):
Ezio Melotti13925002011-03-16 11:05:33 +0200594 #again, just using the main thread, likely they will all be dispatched at
Benjamin Petersona54c9092009-01-13 02:11:23 +0000595 #once. It is ok to ask for too many, because we loop until we find a slot.
596 #the loop can be interrupted to dispatch.
597 #there are only 32 dispatch slots, so we go for twice that!
598 l = []
599 n = 64
600 self.pendingcalls_submit(l, n)
601 self.pendingcalls_wait(l, n)
602
Antoine Pitrou7a2572c2013-08-01 20:43:26 +0200603
604class SubinterpreterTest(unittest.TestCase):
605
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100606 def test_subinterps(self):
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100607 import builtins
608 r, w = os.pipe()
609 code = """if 1:
610 import sys, builtins, pickle
611 with open({:d}, "wb") as f:
612 pickle.dump(id(sys.modules), f)
613 pickle.dump(id(builtins), f)
614 """.format(w)
615 with open(r, "rb") as f:
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100616 ret = support.run_in_subinterp(code)
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100617 self.assertEqual(ret, 0)
618 self.assertNotEqual(pickle.load(f), id(sys.modules))
619 self.assertNotEqual(pickle.load(f), id(builtins))
620
Marcel Plch33e71e02019-05-22 13:51:26 +0200621 def test_mutate_exception(self):
622 """
623 Exceptions saved in global module state get shared between
624 individual module instances. This test checks whether or not
625 a change in one interpreter's module gets reflected into the
626 other ones.
627 """
628 import binascii
629
630 support.run_in_subinterp("import binascii; binascii.Error.foobar = 'foobar'")
631
632 self.assertFalse(hasattr(binascii.Error, "foobar"))
633
Antoine Pitrou7a2572c2013-08-01 20:43:26 +0200634
Ezio Melotti29267c82013-02-23 05:52:46 +0200635class TestThreadState(unittest.TestCase):
636
637 @support.reap_threads
638 def test_thread_state(self):
639 # some extra thread-state tests driven via _testcapi
640 def target():
641 idents = []
642
643 def callback():
Ezio Melotti35246bd2013-02-23 05:58:38 +0200644 idents.append(threading.get_ident())
Ezio Melotti29267c82013-02-23 05:52:46 +0200645
646 _testcapi._test_thread_state(callback)
647 a = b = callback
648 time.sleep(1)
649 # Check our main thread is in the list exactly 3 times.
Ezio Melotti35246bd2013-02-23 05:58:38 +0200650 self.assertEqual(idents.count(threading.get_ident()), 3,
Ezio Melotti29267c82013-02-23 05:52:46 +0200651 "Couldn't find main thread correctly in the list")
652
653 target()
654 t = threading.Thread(target=target)
655 t.start()
656 t.join()
657
Victor Stinner34be8072016-03-14 12:04:26 +0100658
Zachary Warec12f09e2013-11-11 22:47:04 -0600659class Test_testcapi(unittest.TestCase):
Serhiy Storchaka8f7bb102018-08-06 16:50:19 +0300660 locals().update((name, getattr(_testcapi, name))
661 for name in dir(_testcapi)
662 if name.startswith('test_') and not name.endswith('_code'))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000663
Victor Stinner34be8072016-03-14 12:04:26 +0100664
Victor Stinner1ae035b2020-04-17 17:47:20 +0200665class Test_testinternalcapi(unittest.TestCase):
666 locals().update((name, getattr(_testinternalcapi, name))
667 for name in dir(_testinternalcapi)
668 if name.startswith('test_'))
669
670
Victor Stinnerc4aec362016-03-14 22:26:53 +0100671class PyMemDebugTests(unittest.TestCase):
672 PYTHONMALLOC = 'debug'
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100673 # '0x04c06e0' or '04C06E0'
Victor Stinner08572f62016-03-14 21:55:43 +0100674 PTR_REGEX = r'(?:0x)?[0-9a-fA-F]+'
Victor Stinner34be8072016-03-14 12:04:26 +0100675
676 def check(self, code):
677 with support.SuppressCrashReport():
Victor Stinnerc4aec362016-03-14 22:26:53 +0100678 out = assert_python_failure('-c', code,
679 PYTHONMALLOC=self.PYTHONMALLOC)
Victor Stinner34be8072016-03-14 12:04:26 +0100680 stderr = out.err
681 return stderr.decode('ascii', 'replace')
682
683 def test_buffer_overflow(self):
684 out = self.check('import _testcapi; _testcapi.pymem_buffer_overflow()')
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100685 regex = (r"Debug memory block at address p={ptr}: API 'm'\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100686 r" 16 bytes originally requested\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100687 r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n"
688 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 +0100689 r" at tail\+0: 0x78 \*\*\* OUCH\n"
Victor Stinner4c409be2019-04-11 13:01:15 +0200690 r" at tail\+1: 0xfd\n"
691 r" at tail\+2: 0xfd\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100692 r" .*\n"
Victor Stinnere8f9acf2019-04-12 21:54:06 +0200693 r"( The block was made by call #[0-9]+ to debug malloc/realloc.\n)?"
Victor Stinner4c409be2019-04-11 13:01:15 +0200694 r" Data at p: cd cd cd .*\n"
Victor Stinner6453e9e2016-03-15 23:36:28 +0100695 r"\n"
Victor Stinnerf966e532018-11-13 15:14:58 +0100696 r"Enable tracemalloc to get the memory block allocation traceback\n"
697 r"\n"
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100698 r"Fatal Python error: _PyMem_DebugRawFree: bad trailing pad byte")
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100699 regex = regex.format(ptr=self.PTR_REGEX)
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100700 regex = re.compile(regex, flags=re.DOTALL)
Victor Stinner34be8072016-03-14 12:04:26 +0100701 self.assertRegex(out, regex)
702
703 def test_api_misuse(self):
704 out = self.check('import _testcapi; _testcapi.pymem_api_misuse()')
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100705 regex = (r"Debug memory block at address p={ptr}: API 'm'\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100706 r" 16 bytes originally requested\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100707 r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n"
708 r" The [0-9] pad bytes at tail={ptr} are FORBIDDENBYTE, as expected.\n"
Victor Stinnere8f9acf2019-04-12 21:54:06 +0200709 r"( The block was made by call #[0-9]+ to debug malloc/realloc.\n)?"
Victor Stinner4c409be2019-04-11 13:01:15 +0200710 r" Data at p: cd cd cd .*\n"
Victor Stinner6453e9e2016-03-15 23:36:28 +0100711 r"\n"
Victor Stinnerf966e532018-11-13 15:14:58 +0100712 r"Enable tracemalloc to get the memory block allocation traceback\n"
713 r"\n"
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100714 r"Fatal Python error: _PyMem_DebugRawFree: bad ID: Allocated using API 'm', verified using API 'r'\n")
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100715 regex = regex.format(ptr=self.PTR_REGEX)
Victor Stinner34be8072016-03-14 12:04:26 +0100716 self.assertRegex(out, regex)
717
Victor Stinnerad524372016-03-16 12:12:53 +0100718 def check_malloc_without_gil(self, code):
Victor Stinnerc4aec362016-03-14 22:26:53 +0100719 out = self.check(code)
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100720 expected = ('Fatal Python error: _PyMem_DebugMalloc: '
721 'Python memory allocator called without holding the GIL')
Victor Stinnerc4aec362016-03-14 22:26:53 +0100722 self.assertIn(expected, out)
Victor Stinner34be8072016-03-14 12:04:26 +0100723
Victor Stinnerad524372016-03-16 12:12:53 +0100724 def test_pymem_malloc_without_gil(self):
725 # Debug hooks must raise an error if PyMem_Malloc() is called
726 # without holding the GIL
727 code = 'import _testcapi; _testcapi.pymem_malloc_without_gil()'
728 self.check_malloc_without_gil(code)
729
730 def test_pyobject_malloc_without_gil(self):
731 # Debug hooks must raise an error if PyObject_Malloc() is called
732 # without holding the GIL
733 code = 'import _testcapi; _testcapi.pyobject_malloc_without_gil()'
734 self.check_malloc_without_gil(code)
735
Victor Stinner3bf0f3a2019-06-07 16:22:21 +0200736 def check_pyobject_is_freed(self, func_name):
737 code = textwrap.dedent(f'''
Victor Stinner2b00db62019-04-11 11:33:27 +0200738 import gc, os, sys, _testcapi
739 # Disable the GC to avoid crash on GC collection
740 gc.disable()
Victor Stinner3bf0f3a2019-06-07 16:22:21 +0200741 try:
742 _testcapi.{func_name}()
743 # Exit immediately to avoid a crash while deallocating
744 # the invalid object
745 os._exit(0)
746 except _testcapi.error:
747 os._exit(1)
Victor Stinner2b00db62019-04-11 11:33:27 +0200748 ''')
Victor Stinner2b00db62019-04-11 11:33:27 +0200749 assert_python_ok('-c', code, PYTHONMALLOC=self.PYTHONMALLOC)
750
Victor Stinner68762572019-10-07 18:42:01 +0200751 def test_pyobject_null_is_freed(self):
752 self.check_pyobject_is_freed('check_pyobject_null_is_freed')
753
Victor Stinner3bf0f3a2019-06-07 16:22:21 +0200754 def test_pyobject_uninitialized_is_freed(self):
755 self.check_pyobject_is_freed('check_pyobject_uninitialized_is_freed')
Victor Stinner2b00db62019-04-11 11:33:27 +0200756
Victor Stinner3bf0f3a2019-06-07 16:22:21 +0200757 def test_pyobject_forbidden_bytes_is_freed(self):
758 self.check_pyobject_is_freed('check_pyobject_forbidden_bytes_is_freed')
Victor Stinner2b00db62019-04-11 11:33:27 +0200759
Victor Stinner3bf0f3a2019-06-07 16:22:21 +0200760 def test_pyobject_freed_is_freed(self):
761 self.check_pyobject_is_freed('check_pyobject_freed_is_freed')
Victor Stinner2b00db62019-04-11 11:33:27 +0200762
Victor Stinnerc4aec362016-03-14 22:26:53 +0100763
764class PyMemMallocDebugTests(PyMemDebugTests):
765 PYTHONMALLOC = 'malloc_debug'
Victor Stinner34be8072016-03-14 12:04:26 +0100766
767
Victor Stinner5d39e042017-11-29 17:20:38 +0100768@unittest.skipUnless(support.with_pymalloc(), 'need pymalloc')
Victor Stinnerc4aec362016-03-14 22:26:53 +0100769class PyMemPymallocDebugTests(PyMemDebugTests):
770 PYTHONMALLOC = 'pymalloc_debug'
Victor Stinner34be8072016-03-14 12:04:26 +0100771
772
773@unittest.skipUnless(Py_DEBUG, 'need Py_DEBUG')
Victor Stinnerc4aec362016-03-14 22:26:53 +0100774class PyMemDefaultTests(PyMemDebugTests):
775 # test default allocator of Python compiled in debug mode
776 PYTHONMALLOC = ''
Victor Stinner34be8072016-03-14 12:04:26 +0100777
778
Petr Viktorine1becf42020-05-07 15:39:59 +0200779class Test_ModuleStateAccess(unittest.TestCase):
780 """Test access to module start (PEP 573)"""
781
782 # The C part of the tests lives in _testmultiphase, in a module called
783 # _testmultiphase_meth_state_access.
784 # This module has multi-phase initialization, unlike _testcapi.
785
786 def setUp(self):
787 fullname = '_testmultiphase_meth_state_access' # XXX
788 origin = importlib.util.find_spec('_testmultiphase').origin
789 loader = importlib.machinery.ExtensionFileLoader(fullname, origin)
790 spec = importlib.util.spec_from_loader(fullname, loader)
791 module = importlib.util.module_from_spec(spec)
792 loader.exec_module(module)
793 self.module = module
794
795 def test_subclass_get_module(self):
796 """PyType_GetModule for defining_class"""
797 class StateAccessType_Subclass(self.module.StateAccessType):
798 pass
799
800 instance = StateAccessType_Subclass()
801 self.assertIs(instance.get_defining_module(), self.module)
802
803 def test_subclass_get_module_with_super(self):
804 class StateAccessType_Subclass(self.module.StateAccessType):
805 def get_defining_module(self):
806 return super().get_defining_module()
807
808 instance = StateAccessType_Subclass()
809 self.assertIs(instance.get_defining_module(), self.module)
810
811 def test_state_access(self):
812 """Checks methods defined with and without argument clinic
813
814 This tests a no-arg method (get_count) and a method with
815 both a positional and keyword argument.
816 """
817
818 a = self.module.StateAccessType()
819 b = self.module.StateAccessType()
820
821 methods = {
822 'clinic': a.increment_count_clinic,
823 'noclinic': a.increment_count_noclinic,
824 }
825
826 for name, increment_count in methods.items():
827 with self.subTest(name):
828 self.assertEqual(a.get_count(), b.get_count())
829 self.assertEqual(a.get_count(), 0)
830
831 increment_count()
832 self.assertEqual(a.get_count(), b.get_count())
833 self.assertEqual(a.get_count(), 1)
834
835 increment_count(3)
836 self.assertEqual(a.get_count(), b.get_count())
837 self.assertEqual(a.get_count(), 4)
838
839 increment_count(-2, twice=True)
840 self.assertEqual(a.get_count(), b.get_count())
841 self.assertEqual(a.get_count(), 0)
842
843 with self.assertRaises(TypeError):
844 increment_count(thrice=3)
845
846 with self.assertRaises(TypeError):
847 increment_count(1, 2, 3)
848
849
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000850if __name__ == "__main__":
Zachary Warec12f09e2013-11-11 22:47:04 -0600851 unittest.main()