blob: f3d41a20ab0560b67970e33e174f9de44f6c887a [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 Demeyereb65e242019-05-28 14:42:53 +020030Py_TPFLAGS_METHOD_DESCRIPTOR = 1 << 17
31
Benjamin Petersona54c9092009-01-13 02:11:23 +000032
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000033def testfunction(self):
34 """some doc"""
35 return self
36
37class InstanceMethod:
38 id = _testcapi.instancemethod(id)
39 testfunction = _testcapi.instancemethod(testfunction)
40
41class CAPITest(unittest.TestCase):
42
43 def test_instancemethod(self):
44 inst = InstanceMethod()
45 self.assertEqual(id(inst), inst.id())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000046 self.assertTrue(inst.testfunction() is inst)
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000047 self.assertEqual(inst.testfunction.__doc__, testfunction.__doc__)
48 self.assertEqual(InstanceMethod.testfunction.__doc__, testfunction.__doc__)
49
50 InstanceMethod.testfunction.attribute = "test"
51 self.assertEqual(testfunction.attribute, "test")
52 self.assertRaises(AttributeError, setattr, inst.testfunction, "attribute", "test")
53
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000054 def test_no_FatalError_infinite_loop(self):
Antoine Pitrou77e904e2013-10-08 23:04:32 +020055 with support.SuppressCrashReport():
Ezio Melotti25a40452013-03-05 20:26:17 +020056 p = subprocess.Popen([sys.executable, "-c",
Ezio Melottie1857d92013-03-05 20:31:34 +020057 'import _testcapi;'
58 '_testcapi.crash_no_current_thread()'],
59 stdout=subprocess.PIPE,
60 stderr=subprocess.PIPE)
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000061 (out, err) = p.communicate()
62 self.assertEqual(out, b'')
63 # This used to cause an infinite loop.
Vinay Sajip73954042012-05-06 11:34:50 +010064 self.assertTrue(err.rstrip().startswith(
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000065 b'Fatal Python error:'
Vinay Sajip73954042012-05-06 11:34:50 +010066 b' PyThreadState_Get: no current thread'))
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000067
Antoine Pitrou915605c2011-02-24 20:53:48 +000068 def test_memoryview_from_NULL_pointer(self):
69 self.assertRaises(ValueError, _testcapi.make_memoryview_from_NULL_pointer)
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000070
Martin v. Löwisaa2efcb2012-04-19 14:33:43 +020071 def test_exc_info(self):
72 raised_exception = ValueError("5")
73 new_exc = TypeError("TEST")
74 try:
75 raise raised_exception
76 except ValueError as e:
77 tb = e.__traceback__
78 orig_sys_exc_info = sys.exc_info()
79 orig_exc_info = _testcapi.set_exc_info(new_exc.__class__, new_exc, None)
80 new_sys_exc_info = sys.exc_info()
81 new_exc_info = _testcapi.set_exc_info(*orig_exc_info)
82 reset_sys_exc_info = sys.exc_info()
83
84 self.assertEqual(orig_exc_info[1], e)
85
86 self.assertSequenceEqual(orig_exc_info, (raised_exception.__class__, raised_exception, tb))
87 self.assertSequenceEqual(orig_sys_exc_info, orig_exc_info)
88 self.assertSequenceEqual(reset_sys_exc_info, orig_exc_info)
89 self.assertSequenceEqual(new_exc_info, (new_exc.__class__, new_exc, None))
90 self.assertSequenceEqual(new_sys_exc_info, new_exc_info)
91 else:
92 self.assertTrue(False)
93
Stefan Krahfd24f9e2012-08-20 11:04:24 +020094 @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
95 def test_seq_bytes_to_charp_array(self):
96 # Issue #15732: crash in _PySequence_BytesToCharpArray()
97 class Z(object):
98 def __len__(self):
99 return 1
100 self.assertRaises(TypeError, _posixsubprocess.fork_exec,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300101 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 +0200102 # Issue #15736: overflow in _PySequence_BytesToCharpArray()
103 class Z(object):
104 def __len__(self):
105 return sys.maxsize
106 def __getitem__(self, i):
107 return b'x'
108 self.assertRaises(MemoryError, _posixsubprocess.fork_exec,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300109 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 +0200110
Stefan Krahdb579d72012-08-20 14:36:47 +0200111 @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
112 def test_subprocess_fork_exec(self):
113 class Z(object):
114 def __len__(self):
115 return 1
116
117 # Issue #15738: crash in subprocess_fork_exec()
118 self.assertRaises(TypeError, _posixsubprocess.fork_exec,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300119 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 +0200120
Larry Hastingsfcafe432013-11-23 17:35:48 -0800121 @unittest.skipIf(MISSING_C_DOCSTRINGS,
122 "Signature information for builtins requires docstrings")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800123 def test_docstring_signature_parsing(self):
124
125 self.assertEqual(_testcapi.no_docstring.__doc__, None)
126 self.assertEqual(_testcapi.no_docstring.__text_signature__, None)
127
Zachary Ware8ef887c2015-04-13 18:22:35 -0500128 self.assertEqual(_testcapi.docstring_empty.__doc__, None)
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800129 self.assertEqual(_testcapi.docstring_empty.__text_signature__, None)
130
131 self.assertEqual(_testcapi.docstring_no_signature.__doc__,
132 "This docstring has no signature.")
133 self.assertEqual(_testcapi.docstring_no_signature.__text_signature__, None)
134
135 self.assertEqual(_testcapi.docstring_with_invalid_signature.__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800136 "docstring_with_invalid_signature($module, /, boo)\n"
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800137 "\n"
138 "This docstring has an invalid signature."
139 )
140 self.assertEqual(_testcapi.docstring_with_invalid_signature.__text_signature__, None)
141
Larry Hastings2623c8c2014-02-08 22:15:29 -0800142 self.assertEqual(_testcapi.docstring_with_invalid_signature2.__doc__,
143 "docstring_with_invalid_signature2($module, /, boo)\n"
144 "\n"
145 "--\n"
146 "\n"
147 "This docstring also has an invalid signature."
148 )
149 self.assertEqual(_testcapi.docstring_with_invalid_signature2.__text_signature__, None)
150
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800151 self.assertEqual(_testcapi.docstring_with_signature.__doc__,
152 "This docstring has a valid signature.")
Larry Hastings2623c8c2014-02-08 22:15:29 -0800153 self.assertEqual(_testcapi.docstring_with_signature.__text_signature__, "($module, /, sig)")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800154
Zachary Ware8ef887c2015-04-13 18:22:35 -0500155 self.assertEqual(_testcapi.docstring_with_signature_but_no_doc.__doc__, None)
156 self.assertEqual(_testcapi.docstring_with_signature_but_no_doc.__text_signature__,
157 "($module, /, sig)")
158
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800159 self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800160 "\nThis docstring has a valid signature and some extra newlines.")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800161 self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__text_signature__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800162 "($module, /, parameter)")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800163
Benjamin Petersond51374e2014-04-09 23:55:56 -0400164 def test_c_type_with_matrix_multiplication(self):
165 M = _testcapi.matmulType
166 m1 = M()
167 m2 = M()
168 self.assertEqual(m1 @ m2, ("matmul", m1, m2))
169 self.assertEqual(m1 @ 42, ("matmul", m1, 42))
170 self.assertEqual(42 @ m1, ("matmul", 42, m1))
171 o = m1
172 o @= m2
173 self.assertEqual(o, ("imatmul", m1, m2))
174 o = m1
175 o @= 42
176 self.assertEqual(o, ("imatmul", m1, 42))
177 o = 42
178 o @= m1
179 self.assertEqual(o, ("matmul", 42, m1))
180
Victor Stinnerefde1462015-03-21 15:04:43 +0100181 def test_return_null_without_error(self):
182 # Issue #23571: A function must not return NULL without setting an
183 # error
184 if Py_DEBUG:
185 code = textwrap.dedent("""
186 import _testcapi
187 from test import support
188
189 with support.SuppressCrashReport():
190 _testcapi.return_null_without_error()
191 """)
192 rc, out, err = assert_python_failure('-c', code)
Victor Stinner381a9bc2015-03-24 14:01:32 +0100193 self.assertRegex(err.replace(b'\r', b''),
Victor Stinner944fbcc2015-03-24 16:28:52 +0100194 br'Fatal Python error: a function returned NULL '
195 br'without setting an error\n'
Victor Stinner381a9bc2015-03-24 14:01:32 +0100196 br'SystemError: <built-in function '
197 br'return_null_without_error> returned NULL '
198 br'without setting an error\n'
199 br'\n'
200 br'Current thread.*:\n'
201 br' File .*", line 6 in <module>')
Victor Stinnerefde1462015-03-21 15:04:43 +0100202 else:
203 with self.assertRaises(SystemError) as cm:
204 _testcapi.return_null_without_error()
205 self.assertRegex(str(cm.exception),
206 'return_null_without_error.* '
207 'returned NULL without setting an error')
208
209 def test_return_result_with_error(self):
210 # Issue #23571: A function must not return a result with an error set
211 if Py_DEBUG:
212 code = textwrap.dedent("""
213 import _testcapi
214 from test import support
215
216 with support.SuppressCrashReport():
217 _testcapi.return_result_with_error()
218 """)
219 rc, out, err = assert_python_failure('-c', code)
Victor Stinner381a9bc2015-03-24 14:01:32 +0100220 self.assertRegex(err.replace(b'\r', b''),
Victor Stinner944fbcc2015-03-24 16:28:52 +0100221 br'Fatal Python error: a function returned a '
222 br'result with an error set\n'
Victor Stinner381a9bc2015-03-24 14:01:32 +0100223 br'ValueError\n'
224 br'\n'
Serhiy Storchaka467ab192016-10-21 17:09:17 +0300225 br'The above exception was the direct cause '
226 br'of the following exception:\n'
Victor Stinner381a9bc2015-03-24 14:01:32 +0100227 br'\n'
228 br'SystemError: <built-in '
229 br'function return_result_with_error> '
230 br'returned a result with an error set\n'
231 br'\n'
232 br'Current thread.*:\n'
233 br' File .*, line 6 in <module>')
Victor Stinnerefde1462015-03-21 15:04:43 +0100234 else:
235 with self.assertRaises(SystemError) as cm:
236 _testcapi.return_result_with_error()
237 self.assertRegex(str(cm.exception),
238 'return_result_with_error.* '
239 'returned a result with an error set')
240
Serhiy Storchaka13e602e2016-05-20 22:31:14 +0300241 def test_buildvalue_N(self):
242 _testcapi.test_buildvalue_N()
243
xdegaye85f64302017-07-01 14:14:45 +0200244 def test_set_nomemory(self):
245 code = """if 1:
246 import _testcapi
247
248 class C(): pass
249
250 # The first loop tests both functions and that remove_mem_hooks()
251 # can be called twice in a row. The second loop checks a call to
252 # set_nomemory() after a call to remove_mem_hooks(). The third
253 # loop checks the start and stop arguments of set_nomemory().
254 for outer_cnt in range(1, 4):
255 start = 10 * outer_cnt
256 for j in range(100):
257 if j == 0:
258 if outer_cnt != 3:
259 _testcapi.set_nomemory(start)
260 else:
261 _testcapi.set_nomemory(start, start + 1)
262 try:
263 C()
264 except MemoryError as e:
265 if outer_cnt != 3:
266 _testcapi.remove_mem_hooks()
267 print('MemoryError', outer_cnt, j)
268 _testcapi.remove_mem_hooks()
269 break
270 """
271 rc, out, err = assert_python_ok('-c', code)
272 self.assertIn(b'MemoryError 1 10', out)
273 self.assertIn(b'MemoryError 2 20', out)
274 self.assertIn(b'MemoryError 3 30', out)
275
Oren Milman0ccc0f62017-10-08 11:17:46 +0300276 def test_mapping_keys_values_items(self):
277 class Mapping1(dict):
278 def keys(self):
279 return list(super().keys())
280 def values(self):
281 return list(super().values())
282 def items(self):
283 return list(super().items())
284 class Mapping2(dict):
285 def keys(self):
286 return tuple(super().keys())
287 def values(self):
288 return tuple(super().values())
289 def items(self):
290 return tuple(super().items())
291 dict_obj = {'foo': 1, 'bar': 2, 'spam': 3}
292
293 for mapping in [{}, OrderedDict(), Mapping1(), Mapping2(),
294 dict_obj, OrderedDict(dict_obj),
295 Mapping1(dict_obj), Mapping2(dict_obj)]:
296 self.assertListEqual(_testcapi.get_mapping_keys(mapping),
297 list(mapping.keys()))
298 self.assertListEqual(_testcapi.get_mapping_values(mapping),
299 list(mapping.values()))
300 self.assertListEqual(_testcapi.get_mapping_items(mapping),
301 list(mapping.items()))
302
303 def test_mapping_keys_values_items_bad_arg(self):
304 self.assertRaises(AttributeError, _testcapi.get_mapping_keys, None)
305 self.assertRaises(AttributeError, _testcapi.get_mapping_values, None)
306 self.assertRaises(AttributeError, _testcapi.get_mapping_items, None)
307
308 class BadMapping:
309 def keys(self):
310 return None
311 def values(self):
312 return None
313 def items(self):
314 return None
315 bad_mapping = BadMapping()
316 self.assertRaises(TypeError, _testcapi.get_mapping_keys, bad_mapping)
317 self.assertRaises(TypeError, _testcapi.get_mapping_values, bad_mapping)
318 self.assertRaises(TypeError, _testcapi.get_mapping_items, bad_mapping)
319
Victor Stinner18618e652018-10-25 17:28:11 +0200320 @unittest.skipUnless(hasattr(_testcapi, 'negative_refcount'),
321 'need _testcapi.negative_refcount')
322 def test_negative_refcount(self):
323 # bpo-35059: Check that Py_DECREF() reports the correct filename
324 # when calling _Py_NegativeRefcount() to abort Python.
325 code = textwrap.dedent("""
326 import _testcapi
327 from test import support
328
329 with support.SuppressCrashReport():
330 _testcapi.negative_refcount()
331 """)
332 rc, out, err = assert_python_failure('-c', code)
333 self.assertRegex(err,
Victor Stinner3ec9af72018-10-26 02:12:34 +0200334 br'_testcapimodule\.c:[0-9]+: '
Victor Stinnerf1d002c2018-11-21 23:53:44 +0100335 br'_Py_NegativeRefcount: Assertion failed: '
Victor Stinner3ec9af72018-10-26 02:12:34 +0200336 br'object has negative ref count')
Victor Stinner18618e652018-10-25 17:28:11 +0200337
Jeroen Demeyer351c6742019-05-10 19:21:11 +0200338 def test_trashcan_subclass(self):
339 # bpo-35983: Check that the trashcan mechanism for "list" is NOT
340 # activated when its tp_dealloc is being called by a subclass
341 from _testcapi import MyList
342 L = None
343 for i in range(1000):
344 L = MyList((L,))
345
346 def test_trashcan_python_class1(self):
347 self.do_test_trashcan_python_class(list)
348
349 def test_trashcan_python_class2(self):
350 from _testcapi import MyList
351 self.do_test_trashcan_python_class(MyList)
352
353 def do_test_trashcan_python_class(self, base):
354 # Check that the trashcan mechanism works properly for a Python
355 # subclass of a class using the trashcan (this specific test assumes
356 # that the base class "base" behaves like list)
357 class PyList(base):
358 # Count the number of PyList instances to verify that there is
359 # no memory leak
360 num = 0
361 def __init__(self, *args):
362 __class__.num += 1
363 super().__init__(*args)
364 def __del__(self):
365 __class__.num -= 1
366
367 for parity in (0, 1):
368 L = None
369 # We need in the order of 2**20 iterations here such that a
370 # typical 8MB stack would overflow without the trashcan.
371 for i in range(2**20):
372 L = PyList((L,))
373 L.attr = i
374 if parity:
375 # Add one additional nesting layer
376 L = (L,)
377 self.assertGreater(PyList.num, 0)
378 del L
379 self.assertEqual(PyList.num, 0)
380
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800381
Benjamin Petersona54c9092009-01-13 02:11:23 +0000382class TestPendingCalls(unittest.TestCase):
383
384 def pendingcalls_submit(self, l, n):
385 def callback():
386 #this function can be interrupted by thread switching so let's
387 #use an atomic operation
388 l.append(None)
389
390 for i in range(n):
391 time.sleep(random.random()*0.02) #0.01 secs on average
392 #try submitting callback until successful.
393 #rely on regular interrupt to flush queue if we are
394 #unsuccessful.
395 while True:
396 if _testcapi._pending_threadfunc(callback):
397 break;
398
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000399 def pendingcalls_wait(self, l, n, context = None):
Benjamin Petersona54c9092009-01-13 02:11:23 +0000400 #now, stick around until l[0] has grown to 10
401 count = 0;
402 while len(l) != n:
403 #this busy loop is where we expect to be interrupted to
404 #run our callbacks. Note that callbacks are only run on the
405 #main thread
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000406 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +0000407 print("(%i)"%(len(l),),)
408 for i in range(1000):
409 a = i*i
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000410 if context and not context.event.is_set():
411 continue
Benjamin Petersona54c9092009-01-13 02:11:23 +0000412 count += 1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000413 self.assertTrue(count < 10000,
Benjamin Petersona54c9092009-01-13 02:11:23 +0000414 "timeout waiting for %i callbacks, got %i"%(n, len(l)))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000415 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +0000416 print("(%i)"%(len(l),))
417
418 def test_pendingcalls_threaded(self):
Benjamin Petersona54c9092009-01-13 02:11:23 +0000419
420 #do every callback on a separate thread
Eric Snowb75b1a352019-04-12 10:20:10 -0600421 n = 32 #total callbacks
Benjamin Petersona54c9092009-01-13 02:11:23 +0000422 threads = []
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000423 class foo(object):pass
424 context = foo()
425 context.l = []
426 context.n = 2 #submits per thread
427 context.nThreads = n // context.n
428 context.nFinished = 0
429 context.lock = threading.Lock()
430 context.event = threading.Event()
431
Serhiy Storchaka263dcd22015-04-01 13:01:14 +0300432 threads = [threading.Thread(target=self.pendingcalls_thread,
433 args=(context,))
434 for i in range(context.nThreads)]
435 with support.start_threads(threads):
436 self.pendingcalls_wait(context.l, n, context)
Benjamin Petersona54c9092009-01-13 02:11:23 +0000437
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000438 def pendingcalls_thread(self, context):
439 try:
440 self.pendingcalls_submit(context.l, context.n)
441 finally:
442 with context.lock:
443 context.nFinished += 1
444 nFinished = context.nFinished
445 if False and support.verbose:
446 print("finished threads: ", nFinished)
447 if nFinished == context.nThreads:
448 context.event.set()
449
Benjamin Petersona54c9092009-01-13 02:11:23 +0000450 def test_pendingcalls_non_threaded(self):
Ezio Melotti13925002011-03-16 11:05:33 +0200451 #again, just using the main thread, likely they will all be dispatched at
Benjamin Petersona54c9092009-01-13 02:11:23 +0000452 #once. It is ok to ask for too many, because we loop until we find a slot.
453 #the loop can be interrupted to dispatch.
454 #there are only 32 dispatch slots, so we go for twice that!
455 l = []
456 n = 64
457 self.pendingcalls_submit(l, n)
458 self.pendingcalls_wait(l, n)
459
Antoine Pitrou7a2572c2013-08-01 20:43:26 +0200460
Jeroen Demeyereb65e242019-05-28 14:42:53 +0200461class TestPEP590(unittest.TestCase):
462
463 def test_method_descriptor_flag(self):
464 import functools
465 cached = functools.lru_cache(1)(testfunction)
466
467 self.assertFalse(type(repr).__flags__ & Py_TPFLAGS_METHOD_DESCRIPTOR)
468 self.assertTrue(type(list.append).__flags__ & Py_TPFLAGS_METHOD_DESCRIPTOR)
469 self.assertTrue(type(list.__add__).__flags__ & Py_TPFLAGS_METHOD_DESCRIPTOR)
470 self.assertTrue(type(testfunction).__flags__ & Py_TPFLAGS_METHOD_DESCRIPTOR)
471 self.assertTrue(type(cached).__flags__ & Py_TPFLAGS_METHOD_DESCRIPTOR)
472
473 self.assertTrue(_testcapi.MethodDescriptorBase.__flags__ & Py_TPFLAGS_METHOD_DESCRIPTOR)
474 self.assertTrue(_testcapi.MethodDescriptorDerived.__flags__ & Py_TPFLAGS_METHOD_DESCRIPTOR)
475 self.assertFalse(_testcapi.MethodDescriptorNopGet.__flags__ & Py_TPFLAGS_METHOD_DESCRIPTOR)
476
477 # Heap type should not inherit Py_TPFLAGS_METHOD_DESCRIPTOR
478 class MethodDescriptorHeap(_testcapi.MethodDescriptorBase):
479 pass
480 self.assertFalse(MethodDescriptorHeap.__flags__ & Py_TPFLAGS_METHOD_DESCRIPTOR)
481
482
Antoine Pitrou7a2572c2013-08-01 20:43:26 +0200483class SubinterpreterTest(unittest.TestCase):
484
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100485 def test_subinterps(self):
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100486 import builtins
487 r, w = os.pipe()
488 code = """if 1:
489 import sys, builtins, pickle
490 with open({:d}, "wb") as f:
491 pickle.dump(id(sys.modules), f)
492 pickle.dump(id(builtins), f)
493 """.format(w)
494 with open(r, "rb") as f:
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100495 ret = support.run_in_subinterp(code)
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100496 self.assertEqual(ret, 0)
497 self.assertNotEqual(pickle.load(f), id(sys.modules))
498 self.assertNotEqual(pickle.load(f), id(builtins))
499
Marcel Plch33e71e02019-05-22 13:51:26 +0200500 def test_mutate_exception(self):
501 """
502 Exceptions saved in global module state get shared between
503 individual module instances. This test checks whether or not
504 a change in one interpreter's module gets reflected into the
505 other ones.
506 """
507 import binascii
508
509 support.run_in_subinterp("import binascii; binascii.Error.foobar = 'foobar'")
510
511 self.assertFalse(hasattr(binascii.Error, "foobar"))
512
Antoine Pitrou7a2572c2013-08-01 20:43:26 +0200513
Ezio Melotti29267c82013-02-23 05:52:46 +0200514class TestThreadState(unittest.TestCase):
515
516 @support.reap_threads
517 def test_thread_state(self):
518 # some extra thread-state tests driven via _testcapi
519 def target():
520 idents = []
521
522 def callback():
Ezio Melotti35246bd2013-02-23 05:58:38 +0200523 idents.append(threading.get_ident())
Ezio Melotti29267c82013-02-23 05:52:46 +0200524
525 _testcapi._test_thread_state(callback)
526 a = b = callback
527 time.sleep(1)
528 # Check our main thread is in the list exactly 3 times.
Ezio Melotti35246bd2013-02-23 05:58:38 +0200529 self.assertEqual(idents.count(threading.get_ident()), 3,
Ezio Melotti29267c82013-02-23 05:52:46 +0200530 "Couldn't find main thread correctly in the list")
531
532 target()
533 t = threading.Thread(target=target)
534 t.start()
535 t.join()
536
Victor Stinner34be8072016-03-14 12:04:26 +0100537
Zachary Warec12f09e2013-11-11 22:47:04 -0600538class Test_testcapi(unittest.TestCase):
Serhiy Storchaka8f7bb102018-08-06 16:50:19 +0300539 locals().update((name, getattr(_testcapi, name))
540 for name in dir(_testcapi)
541 if name.startswith('test_') and not name.endswith('_code'))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000542
Victor Stinner34be8072016-03-14 12:04:26 +0100543
Victor Stinnerc4aec362016-03-14 22:26:53 +0100544class PyMemDebugTests(unittest.TestCase):
545 PYTHONMALLOC = 'debug'
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100546 # '0x04c06e0' or '04C06E0'
Victor Stinner08572f62016-03-14 21:55:43 +0100547 PTR_REGEX = r'(?:0x)?[0-9a-fA-F]+'
Victor Stinner34be8072016-03-14 12:04:26 +0100548
549 def check(self, code):
550 with support.SuppressCrashReport():
Victor Stinnerc4aec362016-03-14 22:26:53 +0100551 out = assert_python_failure('-c', code,
552 PYTHONMALLOC=self.PYTHONMALLOC)
Victor Stinner34be8072016-03-14 12:04:26 +0100553 stderr = out.err
554 return stderr.decode('ascii', 'replace')
555
556 def test_buffer_overflow(self):
557 out = self.check('import _testcapi; _testcapi.pymem_buffer_overflow()')
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100558 regex = (r"Debug memory block at address p={ptr}: API 'm'\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100559 r" 16 bytes originally requested\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100560 r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n"
561 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 +0100562 r" at tail\+0: 0x78 \*\*\* OUCH\n"
Victor Stinner4c409be2019-04-11 13:01:15 +0200563 r" at tail\+1: 0xfd\n"
564 r" at tail\+2: 0xfd\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100565 r" .*\n"
Victor Stinnere8f9acf2019-04-12 21:54:06 +0200566 r"( The block was made by call #[0-9]+ to debug malloc/realloc.\n)?"
Victor Stinner4c409be2019-04-11 13:01:15 +0200567 r" Data at p: cd cd cd .*\n"
Victor Stinner6453e9e2016-03-15 23:36:28 +0100568 r"\n"
Victor Stinnerf966e532018-11-13 15:14:58 +0100569 r"Enable tracemalloc to get the memory block allocation traceback\n"
570 r"\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100571 r"Fatal Python error: bad trailing pad byte")
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100572 regex = regex.format(ptr=self.PTR_REGEX)
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100573 regex = re.compile(regex, flags=re.DOTALL)
Victor Stinner34be8072016-03-14 12:04:26 +0100574 self.assertRegex(out, regex)
575
576 def test_api_misuse(self):
577 out = self.check('import _testcapi; _testcapi.pymem_api_misuse()')
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100578 regex = (r"Debug memory block at address p={ptr}: API 'm'\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100579 r" 16 bytes originally requested\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100580 r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n"
581 r" The [0-9] pad bytes at tail={ptr} are FORBIDDENBYTE, as expected.\n"
Victor Stinnere8f9acf2019-04-12 21:54:06 +0200582 r"( The block was made by call #[0-9]+ to debug malloc/realloc.\n)?"
Victor Stinner4c409be2019-04-11 13:01:15 +0200583 r" Data at p: cd cd cd .*\n"
Victor Stinner6453e9e2016-03-15 23:36:28 +0100584 r"\n"
Victor Stinnerf966e532018-11-13 15:14:58 +0100585 r"Enable tracemalloc to get the memory block allocation traceback\n"
586 r"\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100587 r"Fatal Python error: bad ID: Allocated using API 'm', verified using API 'r'\n")
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100588 regex = regex.format(ptr=self.PTR_REGEX)
Victor Stinner34be8072016-03-14 12:04:26 +0100589 self.assertRegex(out, regex)
590
Victor Stinnerad524372016-03-16 12:12:53 +0100591 def check_malloc_without_gil(self, code):
Victor Stinnerc4aec362016-03-14 22:26:53 +0100592 out = self.check(code)
593 expected = ('Fatal Python error: Python memory allocator called '
594 'without holding the GIL')
595 self.assertIn(expected, out)
Victor Stinner34be8072016-03-14 12:04:26 +0100596
Victor Stinnerad524372016-03-16 12:12:53 +0100597 def test_pymem_malloc_without_gil(self):
598 # Debug hooks must raise an error if PyMem_Malloc() is called
599 # without holding the GIL
600 code = 'import _testcapi; _testcapi.pymem_malloc_without_gil()'
601 self.check_malloc_without_gil(code)
602
603 def test_pyobject_malloc_without_gil(self):
604 # Debug hooks must raise an error if PyObject_Malloc() is called
605 # without holding the GIL
606 code = 'import _testcapi; _testcapi.pyobject_malloc_without_gil()'
607 self.check_malloc_without_gil(code)
608
Victor Stinner2b00db62019-04-11 11:33:27 +0200609 def check_pyobject_is_freed(self, func):
610 code = textwrap.dedent('''
611 import gc, os, sys, _testcapi
612 # Disable the GC to avoid crash on GC collection
613 gc.disable()
614 obj = _testcapi.{func}()
615 error = (_testcapi.pyobject_is_freed(obj) == False)
616 # Exit immediately to avoid a crash while deallocating
617 # the invalid object
618 os._exit(int(error))
619 ''')
620 code = code.format(func=func)
621 assert_python_ok('-c', code, PYTHONMALLOC=self.PYTHONMALLOC)
622
623 def test_pyobject_is_freed_uninitialized(self):
624 self.check_pyobject_is_freed('pyobject_uninitialized')
625
626 def test_pyobject_is_freed_forbidden_bytes(self):
627 self.check_pyobject_is_freed('pyobject_forbidden_bytes')
628
629 def test_pyobject_is_freed_free(self):
630 self.check_pyobject_is_freed('pyobject_freed')
631
Victor Stinnerc4aec362016-03-14 22:26:53 +0100632
633class PyMemMallocDebugTests(PyMemDebugTests):
634 PYTHONMALLOC = 'malloc_debug'
Victor Stinner34be8072016-03-14 12:04:26 +0100635
636
Victor Stinner5d39e042017-11-29 17:20:38 +0100637@unittest.skipUnless(support.with_pymalloc(), 'need pymalloc')
Victor Stinnerc4aec362016-03-14 22:26:53 +0100638class PyMemPymallocDebugTests(PyMemDebugTests):
639 PYTHONMALLOC = 'pymalloc_debug'
Victor Stinner34be8072016-03-14 12:04:26 +0100640
641
642@unittest.skipUnless(Py_DEBUG, 'need Py_DEBUG')
Victor Stinnerc4aec362016-03-14 22:26:53 +0100643class PyMemDefaultTests(PyMemDebugTests):
644 # test default allocator of Python compiled in debug mode
645 PYTHONMALLOC = ''
Victor Stinner34be8072016-03-14 12:04:26 +0100646
647
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000648if __name__ == "__main__":
Zachary Warec12f09e2013-11-11 22:47:04 -0600649 unittest.main()