blob: 43d7a08da944a90c0ef115afd16f5a80ff5157b2 [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 Stinner34be8072016-03-14 12:04:26 +010011import sysconfig
Victor Stinnerefde1462015-03-21 15:04:43 +010012import textwrap
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020013import threading
Benjamin Petersona54c9092009-01-13 02:11:23 +000014import time
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000015import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +000016from test import support
Larry Hastingsfcafe432013-11-23 17:35:48 -080017from test.support import MISSING_C_DOCSTRINGS
xdegaye85f64302017-07-01 14:14:45 +020018from test.support.script_helper import assert_python_failure, assert_python_ok
Victor Stinner45df8202010-04-28 22:31:17 +000019try:
Stefan Krahfd24f9e2012-08-20 11:04:24 +020020 import _posixsubprocess
21except ImportError:
22 _posixsubprocess = None
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020023
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +020024# Skip this test if the _testcapi module isn't available.
25_testcapi = support.import_module('_testcapi')
Tim Peters9ea17ac2001-02-02 05:57:15 +000026
Victor Stinnerefde1462015-03-21 15:04:43 +010027# Were we compiled --with-pydebug or with #define Py_DEBUG?
28Py_DEBUG = hasattr(sys, 'gettotalrefcount')
29
Jeroen Demeyer735e8af2019-05-30 12:43:19 +020030Py_TPFLAGS_HAVE_VECTORCALL = 1 << 11
Jeroen Demeyereb65e242019-05-28 14:42:53 +020031Py_TPFLAGS_METHOD_DESCRIPTOR = 1 << 17
32
Benjamin Petersona54c9092009-01-13 02:11:23 +000033
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000034def testfunction(self):
35 """some doc"""
36 return self
37
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +020038def testfunction_kw(self, *, kw):
39 """some doc"""
40 return self
41
42
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000043class InstanceMethod:
44 id = _testcapi.instancemethod(id)
45 testfunction = _testcapi.instancemethod(testfunction)
46
47class CAPITest(unittest.TestCase):
48
49 def test_instancemethod(self):
50 inst = InstanceMethod()
51 self.assertEqual(id(inst), inst.id())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000052 self.assertTrue(inst.testfunction() is inst)
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000053 self.assertEqual(inst.testfunction.__doc__, testfunction.__doc__)
54 self.assertEqual(InstanceMethod.testfunction.__doc__, testfunction.__doc__)
55
56 InstanceMethod.testfunction.attribute = "test"
57 self.assertEqual(testfunction.attribute, "test")
58 self.assertRaises(AttributeError, setattr, inst.testfunction, "attribute", "test")
59
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000060 def test_no_FatalError_infinite_loop(self):
Antoine Pitrou77e904e2013-10-08 23:04:32 +020061 with support.SuppressCrashReport():
Ezio Melotti25a40452013-03-05 20:26:17 +020062 p = subprocess.Popen([sys.executable, "-c",
Ezio Melottie1857d92013-03-05 20:31:34 +020063 'import _testcapi;'
64 '_testcapi.crash_no_current_thread()'],
65 stdout=subprocess.PIPE,
66 stderr=subprocess.PIPE)
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000067 (out, err) = p.communicate()
68 self.assertEqual(out, b'')
69 # This used to cause an infinite loop.
Vinay Sajip73954042012-05-06 11:34:50 +010070 self.assertTrue(err.rstrip().startswith(
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000071 b'Fatal Python error:'
Vinay Sajip73954042012-05-06 11:34:50 +010072 b' PyThreadState_Get: no current thread'))
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000073
Antoine Pitrou915605c2011-02-24 20:53:48 +000074 def test_memoryview_from_NULL_pointer(self):
75 self.assertRaises(ValueError, _testcapi.make_memoryview_from_NULL_pointer)
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000076
Martin v. Löwisaa2efcb2012-04-19 14:33:43 +020077 def test_exc_info(self):
78 raised_exception = ValueError("5")
79 new_exc = TypeError("TEST")
80 try:
81 raise raised_exception
82 except ValueError as e:
83 tb = e.__traceback__
84 orig_sys_exc_info = sys.exc_info()
85 orig_exc_info = _testcapi.set_exc_info(new_exc.__class__, new_exc, None)
86 new_sys_exc_info = sys.exc_info()
87 new_exc_info = _testcapi.set_exc_info(*orig_exc_info)
88 reset_sys_exc_info = sys.exc_info()
89
90 self.assertEqual(orig_exc_info[1], e)
91
92 self.assertSequenceEqual(orig_exc_info, (raised_exception.__class__, raised_exception, tb))
93 self.assertSequenceEqual(orig_sys_exc_info, orig_exc_info)
94 self.assertSequenceEqual(reset_sys_exc_info, orig_exc_info)
95 self.assertSequenceEqual(new_exc_info, (new_exc.__class__, new_exc, None))
96 self.assertSequenceEqual(new_sys_exc_info, new_exc_info)
97 else:
98 self.assertTrue(False)
99
Stefan Krahfd24f9e2012-08-20 11:04:24 +0200100 @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
101 def test_seq_bytes_to_charp_array(self):
102 # Issue #15732: crash in _PySequence_BytesToCharpArray()
103 class Z(object):
104 def __len__(self):
105 return 1
106 self.assertRaises(TypeError, _posixsubprocess.fork_exec,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300107 1,Z(),3,(1, 2),5,6,7,8,9,10,11,12,13,14,15,16,17)
Stefan Krah7cacd2e2012-08-21 08:16:09 +0200108 # Issue #15736: overflow in _PySequence_BytesToCharpArray()
109 class Z(object):
110 def __len__(self):
111 return sys.maxsize
112 def __getitem__(self, i):
113 return b'x'
114 self.assertRaises(MemoryError, _posixsubprocess.fork_exec,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300115 1,Z(),3,(1, 2),5,6,7,8,9,10,11,12,13,14,15,16,17)
Stefan Krahfd24f9e2012-08-20 11:04:24 +0200116
Stefan Krahdb579d72012-08-20 14:36:47 +0200117 @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
118 def test_subprocess_fork_exec(self):
119 class Z(object):
120 def __len__(self):
121 return 1
122
123 # Issue #15738: crash in subprocess_fork_exec()
124 self.assertRaises(TypeError, _posixsubprocess.fork_exec,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300125 Z(),[b'1'],3,(1, 2),5,6,7,8,9,10,11,12,13,14,15,16,17)
Stefan Krahdb579d72012-08-20 14:36:47 +0200126
Larry Hastingsfcafe432013-11-23 17:35:48 -0800127 @unittest.skipIf(MISSING_C_DOCSTRINGS,
128 "Signature information for builtins requires docstrings")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800129 def test_docstring_signature_parsing(self):
130
131 self.assertEqual(_testcapi.no_docstring.__doc__, None)
132 self.assertEqual(_testcapi.no_docstring.__text_signature__, None)
133
Zachary Ware8ef887c2015-04-13 18:22:35 -0500134 self.assertEqual(_testcapi.docstring_empty.__doc__, None)
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800135 self.assertEqual(_testcapi.docstring_empty.__text_signature__, None)
136
137 self.assertEqual(_testcapi.docstring_no_signature.__doc__,
138 "This docstring has no signature.")
139 self.assertEqual(_testcapi.docstring_no_signature.__text_signature__, None)
140
141 self.assertEqual(_testcapi.docstring_with_invalid_signature.__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800142 "docstring_with_invalid_signature($module, /, boo)\n"
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800143 "\n"
144 "This docstring has an invalid signature."
145 )
146 self.assertEqual(_testcapi.docstring_with_invalid_signature.__text_signature__, None)
147
Larry Hastings2623c8c2014-02-08 22:15:29 -0800148 self.assertEqual(_testcapi.docstring_with_invalid_signature2.__doc__,
149 "docstring_with_invalid_signature2($module, /, boo)\n"
150 "\n"
151 "--\n"
152 "\n"
153 "This docstring also has an invalid signature."
154 )
155 self.assertEqual(_testcapi.docstring_with_invalid_signature2.__text_signature__, None)
156
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800157 self.assertEqual(_testcapi.docstring_with_signature.__doc__,
158 "This docstring has a valid signature.")
Larry Hastings2623c8c2014-02-08 22:15:29 -0800159 self.assertEqual(_testcapi.docstring_with_signature.__text_signature__, "($module, /, sig)")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800160
Zachary Ware8ef887c2015-04-13 18:22:35 -0500161 self.assertEqual(_testcapi.docstring_with_signature_but_no_doc.__doc__, None)
162 self.assertEqual(_testcapi.docstring_with_signature_but_no_doc.__text_signature__,
163 "($module, /, sig)")
164
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800165 self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800166 "\nThis docstring has a valid signature and some extra newlines.")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800167 self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__text_signature__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800168 "($module, /, parameter)")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800169
Benjamin Petersond51374e2014-04-09 23:55:56 -0400170 def test_c_type_with_matrix_multiplication(self):
171 M = _testcapi.matmulType
172 m1 = M()
173 m2 = M()
174 self.assertEqual(m1 @ m2, ("matmul", m1, m2))
175 self.assertEqual(m1 @ 42, ("matmul", m1, 42))
176 self.assertEqual(42 @ m1, ("matmul", 42, m1))
177 o = m1
178 o @= m2
179 self.assertEqual(o, ("imatmul", m1, m2))
180 o = m1
181 o @= 42
182 self.assertEqual(o, ("imatmul", m1, 42))
183 o = 42
184 o @= m1
185 self.assertEqual(o, ("matmul", 42, m1))
186
Zackery Spytzc7f803b2019-05-31 03:46:36 -0600187 def test_c_type_with_ipow(self):
188 # When the __ipow__ method of a type was implemented in C, using the
189 # modulo param would cause segfaults.
190 o = _testcapi.ipowType()
191 self.assertEqual(o.__ipow__(1), (1, None))
192 self.assertEqual(o.__ipow__(2, 2), (2, 2))
193
Victor Stinnerefde1462015-03-21 15:04:43 +0100194 def test_return_null_without_error(self):
195 # Issue #23571: A function must not return NULL without setting an
196 # error
197 if Py_DEBUG:
198 code = textwrap.dedent("""
199 import _testcapi
200 from test import support
201
202 with support.SuppressCrashReport():
203 _testcapi.return_null_without_error()
204 """)
205 rc, out, err = assert_python_failure('-c', code)
Victor Stinner381a9bc2015-03-24 14:01:32 +0100206 self.assertRegex(err.replace(b'\r', b''),
Victor Stinner944fbcc2015-03-24 16:28:52 +0100207 br'Fatal Python error: a function returned NULL '
208 br'without setting an error\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 Stinner944fbcc2015-03-24 16:28:52 +0100234 br'Fatal Python error: a function returned a '
235 br'result with an error set\n'
Victor Stinner381a9bc2015-03-24 14:01:32 +0100236 br'ValueError\n'
237 br'\n'
Serhiy Storchaka467ab192016-10-21 17:09:17 +0300238 br'The above exception was the direct cause '
239 br'of the following exception:\n'
Victor Stinner381a9bc2015-03-24 14:01:32 +0100240 br'\n'
241 br'SystemError: <built-in '
242 br'function return_result_with_error> '
243 br'returned a result with an error set\n'
244 br'\n'
245 br'Current thread.*:\n'
246 br' File .*, line 6 in <module>')
Victor Stinnerefde1462015-03-21 15:04:43 +0100247 else:
248 with self.assertRaises(SystemError) as cm:
249 _testcapi.return_result_with_error()
250 self.assertRegex(str(cm.exception),
251 'return_result_with_error.* '
252 'returned a result with an error set')
253
Serhiy Storchaka13e602e2016-05-20 22:31:14 +0300254 def test_buildvalue_N(self):
255 _testcapi.test_buildvalue_N()
256
xdegaye85f64302017-07-01 14:14:45 +0200257 def test_set_nomemory(self):
258 code = """if 1:
259 import _testcapi
260
261 class C(): pass
262
263 # The first loop tests both functions and that remove_mem_hooks()
264 # can be called twice in a row. The second loop checks a call to
265 # set_nomemory() after a call to remove_mem_hooks(). The third
266 # loop checks the start and stop arguments of set_nomemory().
267 for outer_cnt in range(1, 4):
268 start = 10 * outer_cnt
269 for j in range(100):
270 if j == 0:
271 if outer_cnt != 3:
272 _testcapi.set_nomemory(start)
273 else:
274 _testcapi.set_nomemory(start, start + 1)
275 try:
276 C()
277 except MemoryError as e:
278 if outer_cnt != 3:
279 _testcapi.remove_mem_hooks()
280 print('MemoryError', outer_cnt, j)
281 _testcapi.remove_mem_hooks()
282 break
283 """
284 rc, out, err = assert_python_ok('-c', code)
285 self.assertIn(b'MemoryError 1 10', out)
286 self.assertIn(b'MemoryError 2 20', out)
287 self.assertIn(b'MemoryError 3 30', out)
288
Oren Milman0ccc0f62017-10-08 11:17:46 +0300289 def test_mapping_keys_values_items(self):
290 class Mapping1(dict):
291 def keys(self):
292 return list(super().keys())
293 def values(self):
294 return list(super().values())
295 def items(self):
296 return list(super().items())
297 class Mapping2(dict):
298 def keys(self):
299 return tuple(super().keys())
300 def values(self):
301 return tuple(super().values())
302 def items(self):
303 return tuple(super().items())
304 dict_obj = {'foo': 1, 'bar': 2, 'spam': 3}
305
306 for mapping in [{}, OrderedDict(), Mapping1(), Mapping2(),
307 dict_obj, OrderedDict(dict_obj),
308 Mapping1(dict_obj), Mapping2(dict_obj)]:
309 self.assertListEqual(_testcapi.get_mapping_keys(mapping),
310 list(mapping.keys()))
311 self.assertListEqual(_testcapi.get_mapping_values(mapping),
312 list(mapping.values()))
313 self.assertListEqual(_testcapi.get_mapping_items(mapping),
314 list(mapping.items()))
315
316 def test_mapping_keys_values_items_bad_arg(self):
317 self.assertRaises(AttributeError, _testcapi.get_mapping_keys, None)
318 self.assertRaises(AttributeError, _testcapi.get_mapping_values, None)
319 self.assertRaises(AttributeError, _testcapi.get_mapping_items, None)
320
321 class BadMapping:
322 def keys(self):
323 return None
324 def values(self):
325 return None
326 def items(self):
327 return None
328 bad_mapping = BadMapping()
329 self.assertRaises(TypeError, _testcapi.get_mapping_keys, bad_mapping)
330 self.assertRaises(TypeError, _testcapi.get_mapping_values, bad_mapping)
331 self.assertRaises(TypeError, _testcapi.get_mapping_items, bad_mapping)
332
Victor Stinner18618e652018-10-25 17:28:11 +0200333 @unittest.skipUnless(hasattr(_testcapi, 'negative_refcount'),
334 'need _testcapi.negative_refcount')
335 def test_negative_refcount(self):
336 # bpo-35059: Check that Py_DECREF() reports the correct filename
337 # when calling _Py_NegativeRefcount() to abort Python.
338 code = textwrap.dedent("""
339 import _testcapi
340 from test import support
341
342 with support.SuppressCrashReport():
343 _testcapi.negative_refcount()
344 """)
345 rc, out, err = assert_python_failure('-c', code)
346 self.assertRegex(err,
Victor Stinner3ec9af72018-10-26 02:12:34 +0200347 br'_testcapimodule\.c:[0-9]+: '
Victor Stinnerf1d002c2018-11-21 23:53:44 +0100348 br'_Py_NegativeRefcount: Assertion failed: '
Victor Stinner3ec9af72018-10-26 02:12:34 +0200349 br'object has negative ref count')
Victor Stinner18618e652018-10-25 17:28:11 +0200350
Jeroen Demeyer351c6742019-05-10 19:21:11 +0200351 def test_trashcan_subclass(self):
352 # bpo-35983: Check that the trashcan mechanism for "list" is NOT
353 # activated when its tp_dealloc is being called by a subclass
354 from _testcapi import MyList
355 L = None
356 for i in range(1000):
357 L = MyList((L,))
358
359 def test_trashcan_python_class1(self):
360 self.do_test_trashcan_python_class(list)
361
362 def test_trashcan_python_class2(self):
363 from _testcapi import MyList
364 self.do_test_trashcan_python_class(MyList)
365
366 def do_test_trashcan_python_class(self, base):
367 # Check that the trashcan mechanism works properly for a Python
368 # subclass of a class using the trashcan (this specific test assumes
369 # that the base class "base" behaves like list)
370 class PyList(base):
371 # Count the number of PyList instances to verify that there is
372 # no memory leak
373 num = 0
374 def __init__(self, *args):
375 __class__.num += 1
376 super().__init__(*args)
377 def __del__(self):
378 __class__.num -= 1
379
380 for parity in (0, 1):
381 L = None
382 # We need in the order of 2**20 iterations here such that a
383 # typical 8MB stack would overflow without the trashcan.
384 for i in range(2**20):
385 L = PyList((L,))
386 L.attr = i
387 if parity:
388 # Add one additional nesting layer
389 L = (L,)
390 self.assertGreater(PyList.num, 0)
391 del L
392 self.assertEqual(PyList.num, 0)
393
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800394
Benjamin Petersona54c9092009-01-13 02:11:23 +0000395class TestPendingCalls(unittest.TestCase):
396
397 def pendingcalls_submit(self, l, n):
398 def callback():
399 #this function can be interrupted by thread switching so let's
400 #use an atomic operation
401 l.append(None)
402
403 for i in range(n):
404 time.sleep(random.random()*0.02) #0.01 secs on average
405 #try submitting callback until successful.
406 #rely on regular interrupt to flush queue if we are
407 #unsuccessful.
408 while True:
409 if _testcapi._pending_threadfunc(callback):
410 break;
411
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000412 def pendingcalls_wait(self, l, n, context = None):
Benjamin Petersona54c9092009-01-13 02:11:23 +0000413 #now, stick around until l[0] has grown to 10
414 count = 0;
415 while len(l) != n:
416 #this busy loop is where we expect to be interrupted to
417 #run our callbacks. Note that callbacks are only run on the
418 #main thread
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000419 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +0000420 print("(%i)"%(len(l),),)
421 for i in range(1000):
422 a = i*i
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000423 if context and not context.event.is_set():
424 continue
Benjamin Petersona54c9092009-01-13 02:11:23 +0000425 count += 1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000426 self.assertTrue(count < 10000,
Benjamin Petersona54c9092009-01-13 02:11:23 +0000427 "timeout waiting for %i callbacks, got %i"%(n, len(l)))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000428 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +0000429 print("(%i)"%(len(l),))
430
431 def test_pendingcalls_threaded(self):
Benjamin Petersona54c9092009-01-13 02:11:23 +0000432
433 #do every callback on a separate thread
Victor Stinnere225beb2019-06-03 18:14:24 +0200434 n = 32 #total callbacks
Benjamin Petersona54c9092009-01-13 02:11:23 +0000435 threads = []
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000436 class foo(object):pass
437 context = foo()
438 context.l = []
439 context.n = 2 #submits per thread
440 context.nThreads = n // context.n
441 context.nFinished = 0
442 context.lock = threading.Lock()
443 context.event = threading.Event()
444
Serhiy Storchaka263dcd22015-04-01 13:01:14 +0300445 threads = [threading.Thread(target=self.pendingcalls_thread,
446 args=(context,))
447 for i in range(context.nThreads)]
448 with support.start_threads(threads):
449 self.pendingcalls_wait(context.l, n, context)
Benjamin Petersona54c9092009-01-13 02:11:23 +0000450
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000451 def pendingcalls_thread(self, context):
452 try:
453 self.pendingcalls_submit(context.l, context.n)
454 finally:
455 with context.lock:
456 context.nFinished += 1
457 nFinished = context.nFinished
458 if False and support.verbose:
459 print("finished threads: ", nFinished)
460 if nFinished == context.nThreads:
461 context.event.set()
462
Benjamin Petersona54c9092009-01-13 02:11:23 +0000463 def test_pendingcalls_non_threaded(self):
Ezio Melotti13925002011-03-16 11:05:33 +0200464 #again, just using the main thread, likely they will all be dispatched at
Benjamin Petersona54c9092009-01-13 02:11:23 +0000465 #once. It is ok to ask for too many, because we loop until we find a slot.
466 #the loop can be interrupted to dispatch.
467 #there are only 32 dispatch slots, so we go for twice that!
468 l = []
469 n = 64
470 self.pendingcalls_submit(l, n)
471 self.pendingcalls_wait(l, n)
472
Antoine Pitrou7a2572c2013-08-01 20:43:26 +0200473
Jeroen Demeyereb65e242019-05-28 14:42:53 +0200474class TestPEP590(unittest.TestCase):
475
476 def test_method_descriptor_flag(self):
477 import functools
478 cached = functools.lru_cache(1)(testfunction)
479
480 self.assertFalse(type(repr).__flags__ & Py_TPFLAGS_METHOD_DESCRIPTOR)
481 self.assertTrue(type(list.append).__flags__ & Py_TPFLAGS_METHOD_DESCRIPTOR)
482 self.assertTrue(type(list.__add__).__flags__ & Py_TPFLAGS_METHOD_DESCRIPTOR)
483 self.assertTrue(type(testfunction).__flags__ & Py_TPFLAGS_METHOD_DESCRIPTOR)
484 self.assertTrue(type(cached).__flags__ & Py_TPFLAGS_METHOD_DESCRIPTOR)
485
486 self.assertTrue(_testcapi.MethodDescriptorBase.__flags__ & Py_TPFLAGS_METHOD_DESCRIPTOR)
487 self.assertTrue(_testcapi.MethodDescriptorDerived.__flags__ & Py_TPFLAGS_METHOD_DESCRIPTOR)
488 self.assertFalse(_testcapi.MethodDescriptorNopGet.__flags__ & Py_TPFLAGS_METHOD_DESCRIPTOR)
489
490 # Heap type should not inherit Py_TPFLAGS_METHOD_DESCRIPTOR
491 class MethodDescriptorHeap(_testcapi.MethodDescriptorBase):
492 pass
493 self.assertFalse(MethodDescriptorHeap.__flags__ & Py_TPFLAGS_METHOD_DESCRIPTOR)
494
Jeroen Demeyer735e8af2019-05-30 12:43:19 +0200495 def test_vectorcall_flag(self):
496 self.assertTrue(_testcapi.MethodDescriptorBase.__flags__ & Py_TPFLAGS_HAVE_VECTORCALL)
497 self.assertTrue(_testcapi.MethodDescriptorDerived.__flags__ & Py_TPFLAGS_HAVE_VECTORCALL)
498 self.assertFalse(_testcapi.MethodDescriptorNopGet.__flags__ & Py_TPFLAGS_HAVE_VECTORCALL)
499 self.assertTrue(_testcapi.MethodDescriptor2.__flags__ & Py_TPFLAGS_HAVE_VECTORCALL)
500
501 # Heap type should not inherit Py_TPFLAGS_HAVE_VECTORCALL
502 class MethodDescriptorHeap(_testcapi.MethodDescriptorBase):
503 pass
504 self.assertFalse(MethodDescriptorHeap.__flags__ & Py_TPFLAGS_HAVE_VECTORCALL)
505
506 def test_vectorcall_override(self):
507 # Check that tp_call can correctly override vectorcall.
508 # MethodDescriptorNopGet implements tp_call but it inherits from
509 # MethodDescriptorBase, which implements vectorcall. Since
510 # MethodDescriptorNopGet returns the args tuple when called, we check
511 # additionally that no new tuple is created for this call.
512 args = tuple(range(5))
513 f = _testcapi.MethodDescriptorNopGet()
514 self.assertIs(f(*args), args)
515
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +0200516 def test_vectorcall(self):
517 # Test a bunch of different ways to call objects:
Petr Viktorinfb9423f2019-06-02 23:52:20 +0200518 # 1. vectorcall using PyVectorcall_Call()
519 # (only for objects that support vectorcall directly)
520 # 2. normal call
521 # 3. vectorcall using _PyObject_Vectorcall()
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +0200522 # 4. call as bound method
523 # 5. call using functools.partial
524
525 # A list of (function, args, kwargs, result) calls to test
526 calls = [(len, (range(42),), {}, 42),
527 (list.append, ([], 0), {}, None),
528 ([].append, (0,), {}, None),
529 (sum, ([36],), {"start":6}, 42),
530 (testfunction, (42,), {}, 42),
Jeroen Demeyer735e8af2019-05-30 12:43:19 +0200531 (testfunction_kw, (42,), {"kw":None}, 42),
532 (_testcapi.MethodDescriptorBase(), (0,), {}, True),
533 (_testcapi.MethodDescriptorDerived(), (0,), {}, True),
534 (_testcapi.MethodDescriptor2(), (0,), {}, False)]
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +0200535
536 from _testcapi import pyobject_vectorcall, pyvectorcall_call
537 from types import MethodType
538 from functools import partial
539
540 def vectorcall(func, args, kwargs):
541 args = *args, *kwargs.values()
542 kwnames = tuple(kwargs)
543 return pyobject_vectorcall(func, args, kwnames)
544
545 for (func, args, kwargs, expected) in calls:
546 with self.subTest(str(func)):
Petr Viktorinfb9423f2019-06-02 23:52:20 +0200547 if not kwargs:
548 self.assertEqual(expected, pyvectorcall_call(func, args))
549 self.assertEqual(expected, pyvectorcall_call(func, args, kwargs))
550
551 # Add derived classes (which do not support vectorcall directly,
552 # but do support all other ways of calling).
553
554 class MethodDescriptorHeap(_testcapi.MethodDescriptorBase):
555 pass
556
557 class MethodDescriptorOverridden(_testcapi.MethodDescriptorBase):
558 def __call__(self, n):
559 return 'new'
560
561 calls += [
562 (MethodDescriptorHeap(), (0,), {}, True),
563 (MethodDescriptorOverridden(), (0,), {}, 'new'),
564 ]
565
566 for (func, args, kwargs, expected) in calls:
567 with self.subTest(str(func)):
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +0200568 args1 = args[1:]
569 meth = MethodType(func, args[0])
570 wrapped = partial(func)
571 if not kwargs:
572 self.assertEqual(expected, func(*args))
573 self.assertEqual(expected, pyobject_vectorcall(func, args, None))
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +0200574 self.assertEqual(expected, meth(*args1))
575 self.assertEqual(expected, wrapped(*args))
576 self.assertEqual(expected, func(*args, **kwargs))
577 self.assertEqual(expected, vectorcall(func, args, kwargs))
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +0200578 self.assertEqual(expected, meth(*args1, **kwargs))
579 self.assertEqual(expected, wrapped(*args, **kwargs))
580
Jeroen Demeyereb65e242019-05-28 14:42:53 +0200581
Antoine Pitrou7a2572c2013-08-01 20:43:26 +0200582class SubinterpreterTest(unittest.TestCase):
583
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100584 def test_subinterps(self):
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100585 import builtins
586 r, w = os.pipe()
587 code = """if 1:
588 import sys, builtins, pickle
589 with open({:d}, "wb") as f:
590 pickle.dump(id(sys.modules), f)
591 pickle.dump(id(builtins), f)
592 """.format(w)
593 with open(r, "rb") as f:
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100594 ret = support.run_in_subinterp(code)
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100595 self.assertEqual(ret, 0)
596 self.assertNotEqual(pickle.load(f), id(sys.modules))
597 self.assertNotEqual(pickle.load(f), id(builtins))
598
Marcel Plch33e71e02019-05-22 13:51:26 +0200599 def test_mutate_exception(self):
600 """
601 Exceptions saved in global module state get shared between
602 individual module instances. This test checks whether or not
603 a change in one interpreter's module gets reflected into the
604 other ones.
605 """
606 import binascii
607
608 support.run_in_subinterp("import binascii; binascii.Error.foobar = 'foobar'")
609
610 self.assertFalse(hasattr(binascii.Error, "foobar"))
611
Antoine Pitrou7a2572c2013-08-01 20:43:26 +0200612
Ezio Melotti29267c82013-02-23 05:52:46 +0200613class TestThreadState(unittest.TestCase):
614
615 @support.reap_threads
616 def test_thread_state(self):
617 # some extra thread-state tests driven via _testcapi
618 def target():
619 idents = []
620
621 def callback():
Ezio Melotti35246bd2013-02-23 05:58:38 +0200622 idents.append(threading.get_ident())
Ezio Melotti29267c82013-02-23 05:52:46 +0200623
624 _testcapi._test_thread_state(callback)
625 a = b = callback
626 time.sleep(1)
627 # Check our main thread is in the list exactly 3 times.
Ezio Melotti35246bd2013-02-23 05:58:38 +0200628 self.assertEqual(idents.count(threading.get_ident()), 3,
Ezio Melotti29267c82013-02-23 05:52:46 +0200629 "Couldn't find main thread correctly in the list")
630
631 target()
632 t = threading.Thread(target=target)
633 t.start()
634 t.join()
635
Victor Stinner34be8072016-03-14 12:04:26 +0100636
Zachary Warec12f09e2013-11-11 22:47:04 -0600637class Test_testcapi(unittest.TestCase):
Serhiy Storchaka8f7bb102018-08-06 16:50:19 +0300638 locals().update((name, getattr(_testcapi, name))
639 for name in dir(_testcapi)
640 if name.startswith('test_') and not name.endswith('_code'))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000641
Victor Stinner34be8072016-03-14 12:04:26 +0100642
Victor Stinnerc4aec362016-03-14 22:26:53 +0100643class PyMemDebugTests(unittest.TestCase):
644 PYTHONMALLOC = 'debug'
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100645 # '0x04c06e0' or '04C06E0'
Victor Stinner08572f62016-03-14 21:55:43 +0100646 PTR_REGEX = r'(?:0x)?[0-9a-fA-F]+'
Victor Stinner34be8072016-03-14 12:04:26 +0100647
648 def check(self, code):
649 with support.SuppressCrashReport():
Victor Stinnerc4aec362016-03-14 22:26:53 +0100650 out = assert_python_failure('-c', code,
651 PYTHONMALLOC=self.PYTHONMALLOC)
Victor Stinner34be8072016-03-14 12:04:26 +0100652 stderr = out.err
653 return stderr.decode('ascii', 'replace')
654
655 def test_buffer_overflow(self):
656 out = self.check('import _testcapi; _testcapi.pymem_buffer_overflow()')
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100657 regex = (r"Debug memory block at address p={ptr}: API 'm'\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100658 r" 16 bytes originally requested\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100659 r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n"
660 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 +0100661 r" at tail\+0: 0x78 \*\*\* OUCH\n"
Victor Stinner4c409be2019-04-11 13:01:15 +0200662 r" at tail\+1: 0xfd\n"
663 r" at tail\+2: 0xfd\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100664 r" .*\n"
Victor Stinnere8f9acf2019-04-12 21:54:06 +0200665 r"( The block was made by call #[0-9]+ to debug malloc/realloc.\n)?"
Victor Stinner4c409be2019-04-11 13:01:15 +0200666 r" Data at p: cd cd cd .*\n"
Victor Stinner6453e9e2016-03-15 23:36:28 +0100667 r"\n"
Victor Stinnerf966e532018-11-13 15:14:58 +0100668 r"Enable tracemalloc to get the memory block allocation traceback\n"
669 r"\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100670 r"Fatal Python error: bad trailing pad byte")
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100671 regex = regex.format(ptr=self.PTR_REGEX)
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100672 regex = re.compile(regex, flags=re.DOTALL)
Victor Stinner34be8072016-03-14 12:04:26 +0100673 self.assertRegex(out, regex)
674
675 def test_api_misuse(self):
676 out = self.check('import _testcapi; _testcapi.pymem_api_misuse()')
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100677 regex = (r"Debug memory block at address p={ptr}: API 'm'\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100678 r" 16 bytes originally requested\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100679 r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n"
680 r" The [0-9] pad bytes at tail={ptr} are FORBIDDENBYTE, as expected.\n"
Victor Stinnere8f9acf2019-04-12 21:54:06 +0200681 r"( The block was made by call #[0-9]+ to debug malloc/realloc.\n)?"
Victor Stinner4c409be2019-04-11 13:01:15 +0200682 r" Data at p: cd cd cd .*\n"
Victor Stinner6453e9e2016-03-15 23:36:28 +0100683 r"\n"
Victor Stinnerf966e532018-11-13 15:14:58 +0100684 r"Enable tracemalloc to get the memory block allocation traceback\n"
685 r"\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100686 r"Fatal Python error: bad ID: Allocated using API 'm', verified using API 'r'\n")
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100687 regex = regex.format(ptr=self.PTR_REGEX)
Victor Stinner34be8072016-03-14 12:04:26 +0100688 self.assertRegex(out, regex)
689
Victor Stinnerad524372016-03-16 12:12:53 +0100690 def check_malloc_without_gil(self, code):
Victor Stinnerc4aec362016-03-14 22:26:53 +0100691 out = self.check(code)
692 expected = ('Fatal Python error: Python memory allocator called '
693 'without holding the GIL')
694 self.assertIn(expected, out)
Victor Stinner34be8072016-03-14 12:04:26 +0100695
Victor Stinnerad524372016-03-16 12:12:53 +0100696 def test_pymem_malloc_without_gil(self):
697 # Debug hooks must raise an error if PyMem_Malloc() is called
698 # without holding the GIL
699 code = 'import _testcapi; _testcapi.pymem_malloc_without_gil()'
700 self.check_malloc_without_gil(code)
701
702 def test_pyobject_malloc_without_gil(self):
703 # Debug hooks must raise an error if PyObject_Malloc() is called
704 # without holding the GIL
705 code = 'import _testcapi; _testcapi.pyobject_malloc_without_gil()'
706 self.check_malloc_without_gil(code)
707
Victor Stinner2b00db62019-04-11 11:33:27 +0200708 def check_pyobject_is_freed(self, func):
709 code = textwrap.dedent('''
710 import gc, os, sys, _testcapi
711 # Disable the GC to avoid crash on GC collection
712 gc.disable()
713 obj = _testcapi.{func}()
714 error = (_testcapi.pyobject_is_freed(obj) == False)
715 # Exit immediately to avoid a crash while deallocating
716 # the invalid object
717 os._exit(int(error))
718 ''')
719 code = code.format(func=func)
720 assert_python_ok('-c', code, PYTHONMALLOC=self.PYTHONMALLOC)
721
722 def test_pyobject_is_freed_uninitialized(self):
723 self.check_pyobject_is_freed('pyobject_uninitialized')
724
725 def test_pyobject_is_freed_forbidden_bytes(self):
726 self.check_pyobject_is_freed('pyobject_forbidden_bytes')
727
728 def test_pyobject_is_freed_free(self):
729 self.check_pyobject_is_freed('pyobject_freed')
730
Victor Stinnerc4aec362016-03-14 22:26:53 +0100731
732class PyMemMallocDebugTests(PyMemDebugTests):
733 PYTHONMALLOC = 'malloc_debug'
Victor Stinner34be8072016-03-14 12:04:26 +0100734
735
Victor Stinner5d39e042017-11-29 17:20:38 +0100736@unittest.skipUnless(support.with_pymalloc(), 'need pymalloc')
Victor Stinnerc4aec362016-03-14 22:26:53 +0100737class PyMemPymallocDebugTests(PyMemDebugTests):
738 PYTHONMALLOC = 'pymalloc_debug'
Victor Stinner34be8072016-03-14 12:04:26 +0100739
740
741@unittest.skipUnless(Py_DEBUG, 'need Py_DEBUG')
Victor Stinnerc4aec362016-03-14 22:26:53 +0100742class PyMemDefaultTests(PyMemDebugTests):
743 # test default allocator of Python compiled in debug mode
744 PYTHONMALLOC = ''
Victor Stinner34be8072016-03-14 12:04:26 +0100745
746
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000747if __name__ == "__main__":
Zachary Warec12f09e2013-11-11 22:47:04 -0600748 unittest.main()