blob: 8bcbd82b2d9dedf49ff2d6ca0529f5e75b048973 [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
Benjamin Petersona54c9092009-01-13 02:11:23 +000030
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000031def testfunction(self):
32 """some doc"""
33 return self
34
35class InstanceMethod:
36 id = _testcapi.instancemethod(id)
37 testfunction = _testcapi.instancemethod(testfunction)
38
39class CAPITest(unittest.TestCase):
40
41 def test_instancemethod(self):
42 inst = InstanceMethod()
43 self.assertEqual(id(inst), inst.id())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000044 self.assertTrue(inst.testfunction() is inst)
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000045 self.assertEqual(inst.testfunction.__doc__, testfunction.__doc__)
46 self.assertEqual(InstanceMethod.testfunction.__doc__, testfunction.__doc__)
47
48 InstanceMethod.testfunction.attribute = "test"
49 self.assertEqual(testfunction.attribute, "test")
50 self.assertRaises(AttributeError, setattr, inst.testfunction, "attribute", "test")
51
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000052 def test_no_FatalError_infinite_loop(self):
Antoine Pitrou77e904e2013-10-08 23:04:32 +020053 with support.SuppressCrashReport():
Ezio Melotti25a40452013-03-05 20:26:17 +020054 p = subprocess.Popen([sys.executable, "-c",
Ezio Melottie1857d92013-03-05 20:31:34 +020055 'import _testcapi;'
56 '_testcapi.crash_no_current_thread()'],
57 stdout=subprocess.PIPE,
58 stderr=subprocess.PIPE)
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000059 (out, err) = p.communicate()
60 self.assertEqual(out, b'')
61 # This used to cause an infinite loop.
Vinay Sajip73954042012-05-06 11:34:50 +010062 self.assertTrue(err.rstrip().startswith(
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000063 b'Fatal Python error:'
Vinay Sajip73954042012-05-06 11:34:50 +010064 b' PyThreadState_Get: no current thread'))
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000065
Antoine Pitrou915605c2011-02-24 20:53:48 +000066 def test_memoryview_from_NULL_pointer(self):
67 self.assertRaises(ValueError, _testcapi.make_memoryview_from_NULL_pointer)
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000068
Martin v. Löwisaa2efcb2012-04-19 14:33:43 +020069 def test_exc_info(self):
70 raised_exception = ValueError("5")
71 new_exc = TypeError("TEST")
72 try:
73 raise raised_exception
74 except ValueError as e:
75 tb = e.__traceback__
76 orig_sys_exc_info = sys.exc_info()
77 orig_exc_info = _testcapi.set_exc_info(new_exc.__class__, new_exc, None)
78 new_sys_exc_info = sys.exc_info()
79 new_exc_info = _testcapi.set_exc_info(*orig_exc_info)
80 reset_sys_exc_info = sys.exc_info()
81
82 self.assertEqual(orig_exc_info[1], e)
83
84 self.assertSequenceEqual(orig_exc_info, (raised_exception.__class__, raised_exception, tb))
85 self.assertSequenceEqual(orig_sys_exc_info, orig_exc_info)
86 self.assertSequenceEqual(reset_sys_exc_info, orig_exc_info)
87 self.assertSequenceEqual(new_exc_info, (new_exc.__class__, new_exc, None))
88 self.assertSequenceEqual(new_sys_exc_info, new_exc_info)
89 else:
90 self.assertTrue(False)
91
Stefan Krahfd24f9e2012-08-20 11:04:24 +020092 @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
93 def test_seq_bytes_to_charp_array(self):
94 # Issue #15732: crash in _PySequence_BytesToCharpArray()
95 class Z(object):
96 def __len__(self):
97 return 1
98 self.assertRaises(TypeError, _posixsubprocess.fork_exec,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +030099 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 +0200100 # Issue #15736: overflow in _PySequence_BytesToCharpArray()
101 class Z(object):
102 def __len__(self):
103 return sys.maxsize
104 def __getitem__(self, i):
105 return b'x'
106 self.assertRaises(MemoryError, _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 Krahfd24f9e2012-08-20 11:04:24 +0200108
Stefan Krahdb579d72012-08-20 14:36:47 +0200109 @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
110 def test_subprocess_fork_exec(self):
111 class Z(object):
112 def __len__(self):
113 return 1
114
115 # Issue #15738: crash in subprocess_fork_exec()
116 self.assertRaises(TypeError, _posixsubprocess.fork_exec,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300117 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 +0200118
Larry Hastingsfcafe432013-11-23 17:35:48 -0800119 @unittest.skipIf(MISSING_C_DOCSTRINGS,
120 "Signature information for builtins requires docstrings")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800121 def test_docstring_signature_parsing(self):
122
123 self.assertEqual(_testcapi.no_docstring.__doc__, None)
124 self.assertEqual(_testcapi.no_docstring.__text_signature__, None)
125
Zachary Ware8ef887c2015-04-13 18:22:35 -0500126 self.assertEqual(_testcapi.docstring_empty.__doc__, None)
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800127 self.assertEqual(_testcapi.docstring_empty.__text_signature__, None)
128
129 self.assertEqual(_testcapi.docstring_no_signature.__doc__,
130 "This docstring has no signature.")
131 self.assertEqual(_testcapi.docstring_no_signature.__text_signature__, None)
132
133 self.assertEqual(_testcapi.docstring_with_invalid_signature.__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800134 "docstring_with_invalid_signature($module, /, boo)\n"
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800135 "\n"
136 "This docstring has an invalid signature."
137 )
138 self.assertEqual(_testcapi.docstring_with_invalid_signature.__text_signature__, None)
139
Larry Hastings2623c8c2014-02-08 22:15:29 -0800140 self.assertEqual(_testcapi.docstring_with_invalid_signature2.__doc__,
141 "docstring_with_invalid_signature2($module, /, boo)\n"
142 "\n"
143 "--\n"
144 "\n"
145 "This docstring also has an invalid signature."
146 )
147 self.assertEqual(_testcapi.docstring_with_invalid_signature2.__text_signature__, None)
148
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800149 self.assertEqual(_testcapi.docstring_with_signature.__doc__,
150 "This docstring has a valid signature.")
Larry Hastings2623c8c2014-02-08 22:15:29 -0800151 self.assertEqual(_testcapi.docstring_with_signature.__text_signature__, "($module, /, sig)")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800152
Zachary Ware8ef887c2015-04-13 18:22:35 -0500153 self.assertEqual(_testcapi.docstring_with_signature_but_no_doc.__doc__, None)
154 self.assertEqual(_testcapi.docstring_with_signature_but_no_doc.__text_signature__,
155 "($module, /, sig)")
156
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800157 self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800158 "\nThis docstring has a valid signature and some extra newlines.")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800159 self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__text_signature__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800160 "($module, /, parameter)")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800161
Benjamin Petersond51374e2014-04-09 23:55:56 -0400162 def test_c_type_with_matrix_multiplication(self):
163 M = _testcapi.matmulType
164 m1 = M()
165 m2 = M()
166 self.assertEqual(m1 @ m2, ("matmul", m1, m2))
167 self.assertEqual(m1 @ 42, ("matmul", m1, 42))
168 self.assertEqual(42 @ m1, ("matmul", 42, m1))
169 o = m1
170 o @= m2
171 self.assertEqual(o, ("imatmul", m1, m2))
172 o = m1
173 o @= 42
174 self.assertEqual(o, ("imatmul", m1, 42))
175 o = 42
176 o @= m1
177 self.assertEqual(o, ("matmul", 42, m1))
178
Victor Stinnerefde1462015-03-21 15:04:43 +0100179 def test_return_null_without_error(self):
180 # Issue #23571: A function must not return NULL without setting an
181 # error
182 if Py_DEBUG:
183 code = textwrap.dedent("""
184 import _testcapi
185 from test import support
186
187 with support.SuppressCrashReport():
188 _testcapi.return_null_without_error()
189 """)
190 rc, out, err = assert_python_failure('-c', code)
Victor Stinner381a9bc2015-03-24 14:01:32 +0100191 self.assertRegex(err.replace(b'\r', b''),
Victor Stinner944fbcc2015-03-24 16:28:52 +0100192 br'Fatal Python error: a function returned NULL '
193 br'without setting an error\n'
Victor Stinner381a9bc2015-03-24 14:01:32 +0100194 br'SystemError: <built-in function '
195 br'return_null_without_error> returned NULL '
196 br'without setting an error\n'
197 br'\n'
198 br'Current thread.*:\n'
199 br' File .*", line 6 in <module>')
Victor Stinnerefde1462015-03-21 15:04:43 +0100200 else:
201 with self.assertRaises(SystemError) as cm:
202 _testcapi.return_null_without_error()
203 self.assertRegex(str(cm.exception),
204 'return_null_without_error.* '
205 'returned NULL without setting an error')
206
207 def test_return_result_with_error(self):
208 # Issue #23571: A function must not return a result with an error set
209 if Py_DEBUG:
210 code = textwrap.dedent("""
211 import _testcapi
212 from test import support
213
214 with support.SuppressCrashReport():
215 _testcapi.return_result_with_error()
216 """)
217 rc, out, err = assert_python_failure('-c', code)
Victor Stinner381a9bc2015-03-24 14:01:32 +0100218 self.assertRegex(err.replace(b'\r', b''),
Victor Stinner944fbcc2015-03-24 16:28:52 +0100219 br'Fatal Python error: a function returned a '
220 br'result with an error set\n'
Victor Stinner381a9bc2015-03-24 14:01:32 +0100221 br'ValueError\n'
222 br'\n'
Serhiy Storchaka467ab192016-10-21 17:09:17 +0300223 br'The above exception was the direct cause '
224 br'of the following exception:\n'
Victor Stinner381a9bc2015-03-24 14:01:32 +0100225 br'\n'
226 br'SystemError: <built-in '
227 br'function return_result_with_error> '
228 br'returned a result with an error set\n'
229 br'\n'
230 br'Current thread.*:\n'
231 br' File .*, line 6 in <module>')
Victor Stinnerefde1462015-03-21 15:04:43 +0100232 else:
233 with self.assertRaises(SystemError) as cm:
234 _testcapi.return_result_with_error()
235 self.assertRegex(str(cm.exception),
236 'return_result_with_error.* '
237 'returned a result with an error set')
238
Serhiy Storchaka13e602e2016-05-20 22:31:14 +0300239 def test_buildvalue_N(self):
240 _testcapi.test_buildvalue_N()
241
xdegaye85f64302017-07-01 14:14:45 +0200242 def test_set_nomemory(self):
243 code = """if 1:
244 import _testcapi
245
246 class C(): pass
247
248 # The first loop tests both functions and that remove_mem_hooks()
249 # can be called twice in a row. The second loop checks a call to
250 # set_nomemory() after a call to remove_mem_hooks(). The third
251 # loop checks the start and stop arguments of set_nomemory().
252 for outer_cnt in range(1, 4):
253 start = 10 * outer_cnt
254 for j in range(100):
255 if j == 0:
256 if outer_cnt != 3:
257 _testcapi.set_nomemory(start)
258 else:
259 _testcapi.set_nomemory(start, start + 1)
260 try:
261 C()
262 except MemoryError as e:
263 if outer_cnt != 3:
264 _testcapi.remove_mem_hooks()
265 print('MemoryError', outer_cnt, j)
266 _testcapi.remove_mem_hooks()
267 break
268 """
269 rc, out, err = assert_python_ok('-c', code)
270 self.assertIn(b'MemoryError 1 10', out)
271 self.assertIn(b'MemoryError 2 20', out)
272 self.assertIn(b'MemoryError 3 30', out)
273
Oren Milman0ccc0f62017-10-08 11:17:46 +0300274 def test_mapping_keys_values_items(self):
275 class Mapping1(dict):
276 def keys(self):
277 return list(super().keys())
278 def values(self):
279 return list(super().values())
280 def items(self):
281 return list(super().items())
282 class Mapping2(dict):
283 def keys(self):
284 return tuple(super().keys())
285 def values(self):
286 return tuple(super().values())
287 def items(self):
288 return tuple(super().items())
289 dict_obj = {'foo': 1, 'bar': 2, 'spam': 3}
290
291 for mapping in [{}, OrderedDict(), Mapping1(), Mapping2(),
292 dict_obj, OrderedDict(dict_obj),
293 Mapping1(dict_obj), Mapping2(dict_obj)]:
294 self.assertListEqual(_testcapi.get_mapping_keys(mapping),
295 list(mapping.keys()))
296 self.assertListEqual(_testcapi.get_mapping_values(mapping),
297 list(mapping.values()))
298 self.assertListEqual(_testcapi.get_mapping_items(mapping),
299 list(mapping.items()))
300
301 def test_mapping_keys_values_items_bad_arg(self):
302 self.assertRaises(AttributeError, _testcapi.get_mapping_keys, None)
303 self.assertRaises(AttributeError, _testcapi.get_mapping_values, None)
304 self.assertRaises(AttributeError, _testcapi.get_mapping_items, None)
305
306 class BadMapping:
307 def keys(self):
308 return None
309 def values(self):
310 return None
311 def items(self):
312 return None
313 bad_mapping = BadMapping()
314 self.assertRaises(TypeError, _testcapi.get_mapping_keys, bad_mapping)
315 self.assertRaises(TypeError, _testcapi.get_mapping_values, bad_mapping)
316 self.assertRaises(TypeError, _testcapi.get_mapping_items, bad_mapping)
317
Victor Stinner18618e652018-10-25 17:28:11 +0200318 @unittest.skipUnless(hasattr(_testcapi, 'negative_refcount'),
319 'need _testcapi.negative_refcount')
320 def test_negative_refcount(self):
321 # bpo-35059: Check that Py_DECREF() reports the correct filename
322 # when calling _Py_NegativeRefcount() to abort Python.
323 code = textwrap.dedent("""
324 import _testcapi
325 from test import support
326
327 with support.SuppressCrashReport():
328 _testcapi.negative_refcount()
329 """)
330 rc, out, err = assert_python_failure('-c', code)
331 self.assertRegex(err,
Victor Stinner3ec9af72018-10-26 02:12:34 +0200332 br'_testcapimodule\.c:[0-9]+: '
Victor Stinnerf1d002c2018-11-21 23:53:44 +0100333 br'_Py_NegativeRefcount: Assertion failed: '
Victor Stinner3ec9af72018-10-26 02:12:34 +0200334 br'object has negative ref count')
Victor Stinner18618e652018-10-25 17:28:11 +0200335
Jeroen Demeyer351c6742019-05-10 19:21:11 +0200336 def test_trashcan_subclass(self):
337 # bpo-35983: Check that the trashcan mechanism for "list" is NOT
338 # activated when its tp_dealloc is being called by a subclass
339 from _testcapi import MyList
340 L = None
341 for i in range(1000):
342 L = MyList((L,))
343
344 def test_trashcan_python_class1(self):
345 self.do_test_trashcan_python_class(list)
346
347 def test_trashcan_python_class2(self):
348 from _testcapi import MyList
349 self.do_test_trashcan_python_class(MyList)
350
351 def do_test_trashcan_python_class(self, base):
352 # Check that the trashcan mechanism works properly for a Python
353 # subclass of a class using the trashcan (this specific test assumes
354 # that the base class "base" behaves like list)
355 class PyList(base):
356 # Count the number of PyList instances to verify that there is
357 # no memory leak
358 num = 0
359 def __init__(self, *args):
360 __class__.num += 1
361 super().__init__(*args)
362 def __del__(self):
363 __class__.num -= 1
364
365 for parity in (0, 1):
366 L = None
367 # We need in the order of 2**20 iterations here such that a
368 # typical 8MB stack would overflow without the trashcan.
369 for i in range(2**20):
370 L = PyList((L,))
371 L.attr = i
372 if parity:
373 # Add one additional nesting layer
374 L = (L,)
375 self.assertGreater(PyList.num, 0)
376 del L
377 self.assertEqual(PyList.num, 0)
378
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800379
Benjamin Petersona54c9092009-01-13 02:11:23 +0000380class TestPendingCalls(unittest.TestCase):
381
382 def pendingcalls_submit(self, l, n):
383 def callback():
384 #this function can be interrupted by thread switching so let's
385 #use an atomic operation
386 l.append(None)
387
388 for i in range(n):
389 time.sleep(random.random()*0.02) #0.01 secs on average
390 #try submitting callback until successful.
391 #rely on regular interrupt to flush queue if we are
392 #unsuccessful.
393 while True:
394 if _testcapi._pending_threadfunc(callback):
395 break;
396
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000397 def pendingcalls_wait(self, l, n, context = None):
Benjamin Petersona54c9092009-01-13 02:11:23 +0000398 #now, stick around until l[0] has grown to 10
399 count = 0;
400 while len(l) != n:
401 #this busy loop is where we expect to be interrupted to
402 #run our callbacks. Note that callbacks are only run on the
403 #main thread
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000404 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +0000405 print("(%i)"%(len(l),),)
406 for i in range(1000):
407 a = i*i
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000408 if context and not context.event.is_set():
409 continue
Benjamin Petersona54c9092009-01-13 02:11:23 +0000410 count += 1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000411 self.assertTrue(count < 10000,
Benjamin Petersona54c9092009-01-13 02:11:23 +0000412 "timeout waiting for %i callbacks, got %i"%(n, len(l)))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000413 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +0000414 print("(%i)"%(len(l),))
415
416 def test_pendingcalls_threaded(self):
Benjamin Petersona54c9092009-01-13 02:11:23 +0000417
418 #do every callback on a separate thread
Eric Snowb75b1a352019-04-12 10:20:10 -0600419 n = 32 #total callbacks
Benjamin Petersona54c9092009-01-13 02:11:23 +0000420 threads = []
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000421 class foo(object):pass
422 context = foo()
423 context.l = []
424 context.n = 2 #submits per thread
425 context.nThreads = n // context.n
426 context.nFinished = 0
427 context.lock = threading.Lock()
428 context.event = threading.Event()
429
Serhiy Storchaka263dcd22015-04-01 13:01:14 +0300430 threads = [threading.Thread(target=self.pendingcalls_thread,
431 args=(context,))
432 for i in range(context.nThreads)]
433 with support.start_threads(threads):
434 self.pendingcalls_wait(context.l, n, context)
Benjamin Petersona54c9092009-01-13 02:11:23 +0000435
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000436 def pendingcalls_thread(self, context):
437 try:
438 self.pendingcalls_submit(context.l, context.n)
439 finally:
440 with context.lock:
441 context.nFinished += 1
442 nFinished = context.nFinished
443 if False and support.verbose:
444 print("finished threads: ", nFinished)
445 if nFinished == context.nThreads:
446 context.event.set()
447
Benjamin Petersona54c9092009-01-13 02:11:23 +0000448 def test_pendingcalls_non_threaded(self):
Ezio Melotti13925002011-03-16 11:05:33 +0200449 #again, just using the main thread, likely they will all be dispatched at
Benjamin Petersona54c9092009-01-13 02:11:23 +0000450 #once. It is ok to ask for too many, because we loop until we find a slot.
451 #the loop can be interrupted to dispatch.
452 #there are only 32 dispatch slots, so we go for twice that!
453 l = []
454 n = 64
455 self.pendingcalls_submit(l, n)
456 self.pendingcalls_wait(l, n)
457
Antoine Pitrou7a2572c2013-08-01 20:43:26 +0200458
459class SubinterpreterTest(unittest.TestCase):
460
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100461 def test_subinterps(self):
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100462 import builtins
463 r, w = os.pipe()
464 code = """if 1:
465 import sys, builtins, pickle
466 with open({:d}, "wb") as f:
467 pickle.dump(id(sys.modules), f)
468 pickle.dump(id(builtins), f)
469 """.format(w)
470 with open(r, "rb") as f:
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100471 ret = support.run_in_subinterp(code)
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100472 self.assertEqual(ret, 0)
473 self.assertNotEqual(pickle.load(f), id(sys.modules))
474 self.assertNotEqual(pickle.load(f), id(builtins))
475
Antoine Pitrou7a2572c2013-08-01 20:43:26 +0200476
Ezio Melotti29267c82013-02-23 05:52:46 +0200477class TestThreadState(unittest.TestCase):
478
479 @support.reap_threads
480 def test_thread_state(self):
481 # some extra thread-state tests driven via _testcapi
482 def target():
483 idents = []
484
485 def callback():
Ezio Melotti35246bd2013-02-23 05:58:38 +0200486 idents.append(threading.get_ident())
Ezio Melotti29267c82013-02-23 05:52:46 +0200487
488 _testcapi._test_thread_state(callback)
489 a = b = callback
490 time.sleep(1)
491 # Check our main thread is in the list exactly 3 times.
Ezio Melotti35246bd2013-02-23 05:58:38 +0200492 self.assertEqual(idents.count(threading.get_ident()), 3,
Ezio Melotti29267c82013-02-23 05:52:46 +0200493 "Couldn't find main thread correctly in the list")
494
495 target()
496 t = threading.Thread(target=target)
497 t.start()
498 t.join()
499
Victor Stinner34be8072016-03-14 12:04:26 +0100500
Zachary Warec12f09e2013-11-11 22:47:04 -0600501class Test_testcapi(unittest.TestCase):
Serhiy Storchaka8f7bb102018-08-06 16:50:19 +0300502 locals().update((name, getattr(_testcapi, name))
503 for name in dir(_testcapi)
504 if name.startswith('test_') and not name.endswith('_code'))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000505
Victor Stinner34be8072016-03-14 12:04:26 +0100506
Victor Stinnerc4aec362016-03-14 22:26:53 +0100507class PyMemDebugTests(unittest.TestCase):
508 PYTHONMALLOC = 'debug'
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100509 # '0x04c06e0' or '04C06E0'
Victor Stinner08572f62016-03-14 21:55:43 +0100510 PTR_REGEX = r'(?:0x)?[0-9a-fA-F]+'
Victor Stinner34be8072016-03-14 12:04:26 +0100511
512 def check(self, code):
513 with support.SuppressCrashReport():
Victor Stinnerc4aec362016-03-14 22:26:53 +0100514 out = assert_python_failure('-c', code,
515 PYTHONMALLOC=self.PYTHONMALLOC)
Victor Stinner34be8072016-03-14 12:04:26 +0100516 stderr = out.err
517 return stderr.decode('ascii', 'replace')
518
519 def test_buffer_overflow(self):
520 out = self.check('import _testcapi; _testcapi.pymem_buffer_overflow()')
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100521 regex = (r"Debug memory block at address p={ptr}: API 'm'\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100522 r" 16 bytes originally requested\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100523 r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n"
524 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 +0100525 r" at tail\+0: 0x78 \*\*\* OUCH\n"
Victor Stinner4c409be2019-04-11 13:01:15 +0200526 r" at tail\+1: 0xfd\n"
527 r" at tail\+2: 0xfd\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100528 r" .*\n"
Victor Stinnere8f9acf2019-04-12 21:54:06 +0200529 r"( The block was made by call #[0-9]+ to debug malloc/realloc.\n)?"
Victor Stinner4c409be2019-04-11 13:01:15 +0200530 r" Data at p: cd cd cd .*\n"
Victor Stinner6453e9e2016-03-15 23:36:28 +0100531 r"\n"
Victor Stinnerf966e532018-11-13 15:14:58 +0100532 r"Enable tracemalloc to get the memory block allocation traceback\n"
533 r"\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100534 r"Fatal Python error: bad trailing pad byte")
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100535 regex = regex.format(ptr=self.PTR_REGEX)
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100536 regex = re.compile(regex, flags=re.DOTALL)
Victor Stinner34be8072016-03-14 12:04:26 +0100537 self.assertRegex(out, regex)
538
539 def test_api_misuse(self):
540 out = self.check('import _testcapi; _testcapi.pymem_api_misuse()')
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100541 regex = (r"Debug memory block at address p={ptr}: API 'm'\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100542 r" 16 bytes originally requested\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100543 r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n"
544 r" The [0-9] pad bytes at tail={ptr} are FORBIDDENBYTE, as expected.\n"
Victor Stinnere8f9acf2019-04-12 21:54:06 +0200545 r"( The block was made by call #[0-9]+ to debug malloc/realloc.\n)?"
Victor Stinner4c409be2019-04-11 13:01:15 +0200546 r" Data at p: cd cd cd .*\n"
Victor Stinner6453e9e2016-03-15 23:36:28 +0100547 r"\n"
Victor Stinnerf966e532018-11-13 15:14:58 +0100548 r"Enable tracemalloc to get the memory block allocation traceback\n"
549 r"\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100550 r"Fatal Python error: bad ID: Allocated using API 'm', verified using API 'r'\n")
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100551 regex = regex.format(ptr=self.PTR_REGEX)
Victor Stinner34be8072016-03-14 12:04:26 +0100552 self.assertRegex(out, regex)
553
Victor Stinnerad524372016-03-16 12:12:53 +0100554 def check_malloc_without_gil(self, code):
Victor Stinnerc4aec362016-03-14 22:26:53 +0100555 out = self.check(code)
556 expected = ('Fatal Python error: Python memory allocator called '
557 'without holding the GIL')
558 self.assertIn(expected, out)
Victor Stinner34be8072016-03-14 12:04:26 +0100559
Victor Stinnerad524372016-03-16 12:12:53 +0100560 def test_pymem_malloc_without_gil(self):
561 # Debug hooks must raise an error if PyMem_Malloc() is called
562 # without holding the GIL
563 code = 'import _testcapi; _testcapi.pymem_malloc_without_gil()'
564 self.check_malloc_without_gil(code)
565
566 def test_pyobject_malloc_without_gil(self):
567 # Debug hooks must raise an error if PyObject_Malloc() is called
568 # without holding the GIL
569 code = 'import _testcapi; _testcapi.pyobject_malloc_without_gil()'
570 self.check_malloc_without_gil(code)
571
Victor Stinner2b00db62019-04-11 11:33:27 +0200572 def check_pyobject_is_freed(self, func):
573 code = textwrap.dedent('''
574 import gc, os, sys, _testcapi
575 # Disable the GC to avoid crash on GC collection
576 gc.disable()
577 obj = _testcapi.{func}()
578 error = (_testcapi.pyobject_is_freed(obj) == False)
579 # Exit immediately to avoid a crash while deallocating
580 # the invalid object
581 os._exit(int(error))
582 ''')
583 code = code.format(func=func)
584 assert_python_ok('-c', code, PYTHONMALLOC=self.PYTHONMALLOC)
585
586 def test_pyobject_is_freed_uninitialized(self):
587 self.check_pyobject_is_freed('pyobject_uninitialized')
588
589 def test_pyobject_is_freed_forbidden_bytes(self):
590 self.check_pyobject_is_freed('pyobject_forbidden_bytes')
591
592 def test_pyobject_is_freed_free(self):
593 self.check_pyobject_is_freed('pyobject_freed')
594
Victor Stinnerc4aec362016-03-14 22:26:53 +0100595
596class PyMemMallocDebugTests(PyMemDebugTests):
597 PYTHONMALLOC = 'malloc_debug'
Victor Stinner34be8072016-03-14 12:04:26 +0100598
599
Victor Stinner5d39e042017-11-29 17:20:38 +0100600@unittest.skipUnless(support.with_pymalloc(), 'need pymalloc')
Victor Stinnerc4aec362016-03-14 22:26:53 +0100601class PyMemPymallocDebugTests(PyMemDebugTests):
602 PYTHONMALLOC = 'pymalloc_debug'
Victor Stinner34be8072016-03-14 12:04:26 +0100603
604
605@unittest.skipUnless(Py_DEBUG, 'need Py_DEBUG')
Victor Stinnerc4aec362016-03-14 22:26:53 +0100606class PyMemDefaultTests(PyMemDebugTests):
607 # test default allocator of Python compiled in debug mode
608 PYTHONMALLOC = ''
Victor Stinner34be8072016-03-14 12:04:26 +0100609
610
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000611if __name__ == "__main__":
Zachary Warec12f09e2013-11-11 22:47:04 -0600612 unittest.main()