blob: c3a04b49df6e8c5fa6d035411b8f312bbf515851 [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
Eric Snowe3774162017-05-22 19:46:40 -07004from collections import namedtuple
Antoine Pitrou8e605772011-04-25 21:21:07 +02005import os
Antoine Pitrou2f828f22012-01-18 00:21:11 +01006import pickle
Eric Snowe3774162017-05-22 19:46:40 -07007import platform
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +00008import random
Victor Stinnerb3adb1a2016-03-14 17:40:09 +01009import re
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000010import subprocess
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +000011import sys
Victor Stinner34be8072016-03-14 12:04:26 +010012import sysconfig
Victor Stinnerefde1462015-03-21 15:04:43 +010013import textwrap
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
23try:
Victor Stinner45df8202010-04-28 22:31:17 +000024 import threading
25except ImportError:
26 threading = None
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +020027# Skip this test if the _testcapi module isn't available.
28_testcapi = support.import_module('_testcapi')
Tim Peters9ea17ac2001-02-02 05:57:15 +000029
Victor Stinnerefde1462015-03-21 15:04:43 +010030# Were we compiled --with-pydebug or with #define Py_DEBUG?
31Py_DEBUG = hasattr(sys, 'gettotalrefcount')
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
38class InstanceMethod:
39 id = _testcapi.instancemethod(id)
40 testfunction = _testcapi.instancemethod(testfunction)
41
42class CAPITest(unittest.TestCase):
43
44 def test_instancemethod(self):
45 inst = InstanceMethod()
46 self.assertEqual(id(inst), inst.id())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000047 self.assertTrue(inst.testfunction() is inst)
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000048 self.assertEqual(inst.testfunction.__doc__, testfunction.__doc__)
49 self.assertEqual(InstanceMethod.testfunction.__doc__, testfunction.__doc__)
50
51 InstanceMethod.testfunction.attribute = "test"
52 self.assertEqual(testfunction.attribute, "test")
53 self.assertRaises(AttributeError, setattr, inst.testfunction, "attribute", "test")
54
Stefan Krah0ca46242010-06-09 08:56:28 +000055 @unittest.skipUnless(threading, 'Threading required for this test.')
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000056 def test_no_FatalError_infinite_loop(self):
Antoine Pitrou77e904e2013-10-08 23:04:32 +020057 with support.SuppressCrashReport():
Ezio Melotti25a40452013-03-05 20:26:17 +020058 p = subprocess.Popen([sys.executable, "-c",
Ezio Melottie1857d92013-03-05 20:31:34 +020059 'import _testcapi;'
60 '_testcapi.crash_no_current_thread()'],
61 stdout=subprocess.PIPE,
62 stderr=subprocess.PIPE)
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000063 (out, err) = p.communicate()
64 self.assertEqual(out, b'')
65 # This used to cause an infinite loop.
Vinay Sajip73954042012-05-06 11:34:50 +010066 self.assertTrue(err.rstrip().startswith(
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000067 b'Fatal Python error:'
Vinay Sajip73954042012-05-06 11:34:50 +010068 b' PyThreadState_Get: no current thread'))
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000069
Antoine Pitrou915605c2011-02-24 20:53:48 +000070 def test_memoryview_from_NULL_pointer(self):
71 self.assertRaises(ValueError, _testcapi.make_memoryview_from_NULL_pointer)
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000072
Martin v. Löwisaa2efcb2012-04-19 14:33:43 +020073 def test_exc_info(self):
74 raised_exception = ValueError("5")
75 new_exc = TypeError("TEST")
76 try:
77 raise raised_exception
78 except ValueError as e:
79 tb = e.__traceback__
80 orig_sys_exc_info = sys.exc_info()
81 orig_exc_info = _testcapi.set_exc_info(new_exc.__class__, new_exc, None)
82 new_sys_exc_info = sys.exc_info()
83 new_exc_info = _testcapi.set_exc_info(*orig_exc_info)
84 reset_sys_exc_info = sys.exc_info()
85
86 self.assertEqual(orig_exc_info[1], e)
87
88 self.assertSequenceEqual(orig_exc_info, (raised_exception.__class__, raised_exception, tb))
89 self.assertSequenceEqual(orig_sys_exc_info, orig_exc_info)
90 self.assertSequenceEqual(reset_sys_exc_info, orig_exc_info)
91 self.assertSequenceEqual(new_exc_info, (new_exc.__class__, new_exc, None))
92 self.assertSequenceEqual(new_sys_exc_info, new_exc_info)
93 else:
94 self.assertTrue(False)
95
Stefan Krahfd24f9e2012-08-20 11:04:24 +020096 @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
97 def test_seq_bytes_to_charp_array(self):
98 # Issue #15732: crash in _PySequence_BytesToCharpArray()
99 class Z(object):
100 def __len__(self):
101 return 1
102 self.assertRaises(TypeError, _posixsubprocess.fork_exec,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300103 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 +0200104 # Issue #15736: overflow in _PySequence_BytesToCharpArray()
105 class Z(object):
106 def __len__(self):
107 return sys.maxsize
108 def __getitem__(self, i):
109 return b'x'
110 self.assertRaises(MemoryError, _posixsubprocess.fork_exec,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300111 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 +0200112
Stefan Krahdb579d72012-08-20 14:36:47 +0200113 @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
114 def test_subprocess_fork_exec(self):
115 class Z(object):
116 def __len__(self):
117 return 1
118
119 # Issue #15738: crash in subprocess_fork_exec()
120 self.assertRaises(TypeError, _posixsubprocess.fork_exec,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300121 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 +0200122
Larry Hastingsfcafe432013-11-23 17:35:48 -0800123 @unittest.skipIf(MISSING_C_DOCSTRINGS,
124 "Signature information for builtins requires docstrings")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800125 def test_docstring_signature_parsing(self):
126
127 self.assertEqual(_testcapi.no_docstring.__doc__, None)
128 self.assertEqual(_testcapi.no_docstring.__text_signature__, None)
129
Zachary Ware8ef887c2015-04-13 18:22:35 -0500130 self.assertEqual(_testcapi.docstring_empty.__doc__, None)
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800131 self.assertEqual(_testcapi.docstring_empty.__text_signature__, None)
132
133 self.assertEqual(_testcapi.docstring_no_signature.__doc__,
134 "This docstring has no signature.")
135 self.assertEqual(_testcapi.docstring_no_signature.__text_signature__, None)
136
137 self.assertEqual(_testcapi.docstring_with_invalid_signature.__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800138 "docstring_with_invalid_signature($module, /, boo)\n"
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800139 "\n"
140 "This docstring has an invalid signature."
141 )
142 self.assertEqual(_testcapi.docstring_with_invalid_signature.__text_signature__, None)
143
Larry Hastings2623c8c2014-02-08 22:15:29 -0800144 self.assertEqual(_testcapi.docstring_with_invalid_signature2.__doc__,
145 "docstring_with_invalid_signature2($module, /, boo)\n"
146 "\n"
147 "--\n"
148 "\n"
149 "This docstring also has an invalid signature."
150 )
151 self.assertEqual(_testcapi.docstring_with_invalid_signature2.__text_signature__, None)
152
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800153 self.assertEqual(_testcapi.docstring_with_signature.__doc__,
154 "This docstring has a valid signature.")
Larry Hastings2623c8c2014-02-08 22:15:29 -0800155 self.assertEqual(_testcapi.docstring_with_signature.__text_signature__, "($module, /, sig)")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800156
Zachary Ware8ef887c2015-04-13 18:22:35 -0500157 self.assertEqual(_testcapi.docstring_with_signature_but_no_doc.__doc__, None)
158 self.assertEqual(_testcapi.docstring_with_signature_but_no_doc.__text_signature__,
159 "($module, /, sig)")
160
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800161 self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800162 "\nThis docstring has a valid signature and some extra newlines.")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800163 self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__text_signature__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800164 "($module, /, parameter)")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800165
Benjamin Petersond51374e2014-04-09 23:55:56 -0400166 def test_c_type_with_matrix_multiplication(self):
167 M = _testcapi.matmulType
168 m1 = M()
169 m2 = M()
170 self.assertEqual(m1 @ m2, ("matmul", m1, m2))
171 self.assertEqual(m1 @ 42, ("matmul", m1, 42))
172 self.assertEqual(42 @ m1, ("matmul", 42, m1))
173 o = m1
174 o @= m2
175 self.assertEqual(o, ("imatmul", m1, m2))
176 o = m1
177 o @= 42
178 self.assertEqual(o, ("imatmul", m1, 42))
179 o = 42
180 o @= m1
181 self.assertEqual(o, ("matmul", 42, m1))
182
Victor Stinnerefde1462015-03-21 15:04:43 +0100183 def test_return_null_without_error(self):
184 # Issue #23571: A function must not return NULL without setting an
185 # error
186 if Py_DEBUG:
187 code = textwrap.dedent("""
188 import _testcapi
189 from test import support
190
191 with support.SuppressCrashReport():
192 _testcapi.return_null_without_error()
193 """)
194 rc, out, err = assert_python_failure('-c', code)
Victor Stinner381a9bc2015-03-24 14:01:32 +0100195 self.assertRegex(err.replace(b'\r', b''),
Victor Stinner944fbcc2015-03-24 16:28:52 +0100196 br'Fatal Python error: a function returned NULL '
197 br'without setting an error\n'
Victor Stinner381a9bc2015-03-24 14:01:32 +0100198 br'SystemError: <built-in function '
199 br'return_null_without_error> returned NULL '
200 br'without setting an error\n'
201 br'\n'
202 br'Current thread.*:\n'
203 br' File .*", line 6 in <module>')
Victor Stinnerefde1462015-03-21 15:04:43 +0100204 else:
205 with self.assertRaises(SystemError) as cm:
206 _testcapi.return_null_without_error()
207 self.assertRegex(str(cm.exception),
208 'return_null_without_error.* '
209 'returned NULL without setting an error')
210
211 def test_return_result_with_error(self):
212 # Issue #23571: A function must not return a result with an error set
213 if Py_DEBUG:
214 code = textwrap.dedent("""
215 import _testcapi
216 from test import support
217
218 with support.SuppressCrashReport():
219 _testcapi.return_result_with_error()
220 """)
221 rc, out, err = assert_python_failure('-c', code)
Victor Stinner381a9bc2015-03-24 14:01:32 +0100222 self.assertRegex(err.replace(b'\r', b''),
Victor Stinner944fbcc2015-03-24 16:28:52 +0100223 br'Fatal Python error: a function returned a '
224 br'result with an error set\n'
Victor Stinner381a9bc2015-03-24 14:01:32 +0100225 br'ValueError\n'
226 br'\n'
Serhiy Storchaka467ab192016-10-21 17:09:17 +0300227 br'The above exception was the direct cause '
228 br'of the following exception:\n'
Victor Stinner381a9bc2015-03-24 14:01:32 +0100229 br'\n'
230 br'SystemError: <built-in '
231 br'function return_result_with_error> '
232 br'returned a result with an error set\n'
233 br'\n'
234 br'Current thread.*:\n'
235 br' File .*, line 6 in <module>')
Victor Stinnerefde1462015-03-21 15:04:43 +0100236 else:
237 with self.assertRaises(SystemError) as cm:
238 _testcapi.return_result_with_error()
239 self.assertRegex(str(cm.exception),
240 'return_result_with_error.* '
241 'returned a result with an error set')
242
Serhiy Storchaka13e602e2016-05-20 22:31:14 +0300243 def test_buildvalue_N(self):
244 _testcapi.test_buildvalue_N()
245
xdegaye85f64302017-07-01 14:14:45 +0200246 def test_set_nomemory(self):
247 code = """if 1:
248 import _testcapi
249
250 class C(): pass
251
252 # The first loop tests both functions and that remove_mem_hooks()
253 # can be called twice in a row. The second loop checks a call to
254 # set_nomemory() after a call to remove_mem_hooks(). The third
255 # loop checks the start and stop arguments of set_nomemory().
256 for outer_cnt in range(1, 4):
257 start = 10 * outer_cnt
258 for j in range(100):
259 if j == 0:
260 if outer_cnt != 3:
261 _testcapi.set_nomemory(start)
262 else:
263 _testcapi.set_nomemory(start, start + 1)
264 try:
265 C()
266 except MemoryError as e:
267 if outer_cnt != 3:
268 _testcapi.remove_mem_hooks()
269 print('MemoryError', outer_cnt, j)
270 _testcapi.remove_mem_hooks()
271 break
272 """
273 rc, out, err = assert_python_ok('-c', code)
274 self.assertIn(b'MemoryError 1 10', out)
275 self.assertIn(b'MemoryError 2 20', out)
276 self.assertIn(b'MemoryError 3 30', out)
277
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800278
Victor Stinner45df8202010-04-28 22:31:17 +0000279@unittest.skipUnless(threading, 'Threading required for this test.')
Benjamin Petersona54c9092009-01-13 02:11:23 +0000280class TestPendingCalls(unittest.TestCase):
281
282 def pendingcalls_submit(self, l, n):
283 def callback():
284 #this function can be interrupted by thread switching so let's
285 #use an atomic operation
286 l.append(None)
287
288 for i in range(n):
289 time.sleep(random.random()*0.02) #0.01 secs on average
290 #try submitting callback until successful.
291 #rely on regular interrupt to flush queue if we are
292 #unsuccessful.
293 while True:
294 if _testcapi._pending_threadfunc(callback):
295 break;
296
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000297 def pendingcalls_wait(self, l, n, context = None):
Benjamin Petersona54c9092009-01-13 02:11:23 +0000298 #now, stick around until l[0] has grown to 10
299 count = 0;
300 while len(l) != n:
301 #this busy loop is where we expect to be interrupted to
302 #run our callbacks. Note that callbacks are only run on the
303 #main thread
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000304 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +0000305 print("(%i)"%(len(l),),)
306 for i in range(1000):
307 a = i*i
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000308 if context and not context.event.is_set():
309 continue
Benjamin Petersona54c9092009-01-13 02:11:23 +0000310 count += 1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000311 self.assertTrue(count < 10000,
Benjamin Petersona54c9092009-01-13 02:11:23 +0000312 "timeout waiting for %i callbacks, got %i"%(n, len(l)))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000313 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +0000314 print("(%i)"%(len(l),))
315
316 def test_pendingcalls_threaded(self):
Benjamin Petersona54c9092009-01-13 02:11:23 +0000317
318 #do every callback on a separate thread
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000319 n = 32 #total callbacks
Benjamin Petersona54c9092009-01-13 02:11:23 +0000320 threads = []
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000321 class foo(object):pass
322 context = foo()
323 context.l = []
324 context.n = 2 #submits per thread
325 context.nThreads = n // context.n
326 context.nFinished = 0
327 context.lock = threading.Lock()
328 context.event = threading.Event()
329
Serhiy Storchaka263dcd22015-04-01 13:01:14 +0300330 threads = [threading.Thread(target=self.pendingcalls_thread,
331 args=(context,))
332 for i in range(context.nThreads)]
333 with support.start_threads(threads):
334 self.pendingcalls_wait(context.l, n, context)
Benjamin Petersona54c9092009-01-13 02:11:23 +0000335
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000336 def pendingcalls_thread(self, context):
337 try:
338 self.pendingcalls_submit(context.l, context.n)
339 finally:
340 with context.lock:
341 context.nFinished += 1
342 nFinished = context.nFinished
343 if False and support.verbose:
344 print("finished threads: ", nFinished)
345 if nFinished == context.nThreads:
346 context.event.set()
347
Benjamin Petersona54c9092009-01-13 02:11:23 +0000348 def test_pendingcalls_non_threaded(self):
Ezio Melotti13925002011-03-16 11:05:33 +0200349 #again, just using the main thread, likely they will all be dispatched at
Benjamin Petersona54c9092009-01-13 02:11:23 +0000350 #once. It is ok to ask for too many, because we loop until we find a slot.
351 #the loop can be interrupted to dispatch.
352 #there are only 32 dispatch slots, so we go for twice that!
353 l = []
354 n = 64
355 self.pendingcalls_submit(l, n)
356 self.pendingcalls_wait(l, n)
357
Antoine Pitrou7a2572c2013-08-01 20:43:26 +0200358
359class SubinterpreterTest(unittest.TestCase):
360
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100361 def test_subinterps(self):
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100362 import builtins
363 r, w = os.pipe()
364 code = """if 1:
365 import sys, builtins, pickle
366 with open({:d}, "wb") as f:
367 pickle.dump(id(sys.modules), f)
368 pickle.dump(id(builtins), f)
369 """.format(w)
370 with open(r, "rb") as f:
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100371 ret = support.run_in_subinterp(code)
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100372 self.assertEqual(ret, 0)
373 self.assertNotEqual(pickle.load(f), id(sys.modules))
374 self.assertNotEqual(pickle.load(f), id(builtins))
375
Antoine Pitrou7a2572c2013-08-01 20:43:26 +0200376
Martin v. Löwisc15bdef2009-05-29 14:47:46 +0000377# Bug #6012
378class Test6012(unittest.TestCase):
379 def test(self):
380 self.assertEqual(_testcapi.argparsing("Hello", "World"), 1)
Benjamin Petersona54c9092009-01-13 02:11:23 +0000381
Antoine Pitrou8e605772011-04-25 21:21:07 +0200382
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000383class EmbeddingTests(unittest.TestCase):
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000384 def setUp(self):
Zachary Ware6d8a2602015-12-05 00:16:55 -0600385 here = os.path.abspath(__file__)
386 basepath = os.path.dirname(os.path.dirname(os.path.dirname(here)))
Nick Coghlan4e641df2013-11-03 16:54:46 +1000387 exename = "_testembed"
388 if sys.platform.startswith("win"):
389 ext = ("_d" if "_d" in sys.executable else "") + ".exe"
390 exename += ext
391 exepath = os.path.dirname(sys.executable)
392 else:
Nick Coghlanbca9acf2014-09-25 19:48:15 +1000393 exepath = os.path.join(basepath, "Programs")
Nick Coghlan4e641df2013-11-03 16:54:46 +1000394 self.test_exe = exe = os.path.join(exepath, exename)
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000395 if not os.path.exists(exe):
396 self.skipTest("%r doesn't exist" % exe)
Antoine Pitrou8e605772011-04-25 21:21:07 +0200397 # This is needed otherwise we get a fatal error:
398 # "Py_Initialize: Unable to get the locale encoding
399 # LookupError: no codec search functions registered: can't find encoding"
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000400 self.oldcwd = os.getcwd()
Antoine Pitrou8e605772011-04-25 21:21:07 +0200401 os.chdir(basepath)
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000402
403 def tearDown(self):
404 os.chdir(self.oldcwd)
405
Nick Coghlan6ea41862017-06-11 13:16:15 +1000406 def run_embedded_interpreter(self, *args, env=None):
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000407 """Runs a test in the embedded interpreter"""
408 cmd = [self.test_exe]
409 cmd.extend(args)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000410 if env is not None and sys.platform == 'win32':
411 # Windows requires at least the SYSTEMROOT environment variable to
412 # start Python.
413 env = env.copy()
414 env['SYSTEMROOT'] = os.environ['SYSTEMROOT']
415
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000416 p = subprocess.Popen(cmd,
417 stdout=subprocess.PIPE,
Steve Dower86e9deb2014-11-01 15:11:05 -0700418 stderr=subprocess.PIPE,
Nick Coghlan6ea41862017-06-11 13:16:15 +1000419 universal_newlines=True,
420 env=env)
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000421 (out, err) = p.communicate()
422 self.assertEqual(p.returncode, 0,
423 "bad returncode %d, stderr is %r" %
424 (p.returncode, err))
Steve Dower86e9deb2014-11-01 15:11:05 -0700425 return out, err
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000426
Eric Snowd1c3c132017-05-24 17:19:47 -0700427 def run_repeated_init_and_subinterpreters(self):
Steve Dowerea74f0c2017-01-01 20:25:03 -0800428 out, err = self.run_embedded_interpreter("repeated_init_and_subinterpreters")
Eric Snowe3774162017-05-22 19:46:40 -0700429 self.assertEqual(err, "")
430
431 # The output from _testembed looks like this:
432 # --- Pass 0 ---
433 # interp 0 <0x1cf9330>, thread state <0x1cf9700>: id(modules) = 139650431942728
434 # interp 1 <0x1d4f690>, thread state <0x1d35350>: id(modules) = 139650431165784
435 # interp 2 <0x1d5a690>, thread state <0x1d99ed0>: id(modules) = 139650413140368
436 # interp 3 <0x1d4f690>, thread state <0x1dc3340>: id(modules) = 139650412862200
437 # interp 0 <0x1cf9330>, thread state <0x1cf9700>: id(modules) = 139650431942728
438 # --- Pass 1 ---
439 # ...
440
441 interp_pat = (r"^interp (\d+) <(0x[\dA-F]+)>, "
442 r"thread state <(0x[\dA-F]+)>: "
443 r"id\(modules\) = ([\d]+)$")
444 Interp = namedtuple("Interp", "id interp tstate modules")
445
Eric Snowe3774162017-05-22 19:46:40 -0700446 numloops = 0
Eric Snowd1c3c132017-05-24 17:19:47 -0700447 current_run = []
Eric Snowe3774162017-05-22 19:46:40 -0700448 for line in out.splitlines():
449 if line == "--- Pass {} ---".format(numloops):
Eric Snowd1c3c132017-05-24 17:19:47 -0700450 self.assertEqual(len(current_run), 0)
Eric Snowe3774162017-05-22 19:46:40 -0700451 if support.verbose:
452 print(line)
Eric Snowe3774162017-05-22 19:46:40 -0700453 numloops += 1
Eric Snowe3774162017-05-22 19:46:40 -0700454 continue
Eric Snowe3774162017-05-22 19:46:40 -0700455
Eric Snowd1c3c132017-05-24 17:19:47 -0700456 self.assertLess(len(current_run), 5)
Eric Snowe3774162017-05-22 19:46:40 -0700457 match = re.match(interp_pat, line)
458 if match is None:
459 self.assertRegex(line, interp_pat)
460
Eric Snowe3774162017-05-22 19:46:40 -0700461 # Parse the line from the loop. The first line is the main
462 # interpreter and the 3 afterward are subinterpreters.
463 interp = Interp(*match.groups())
464 if support.verbose:
465 print(interp)
Eric Snowe3774162017-05-22 19:46:40 -0700466 self.assertTrue(interp.interp)
467 self.assertTrue(interp.tstate)
468 self.assertTrue(interp.modules)
Eric Snowd1c3c132017-05-24 17:19:47 -0700469 current_run.append(interp)
470
471 # The last line in the loop should be the same as the first.
472 if len(current_run) == 5:
473 main = current_run[0]
474 self.assertEqual(interp, main)
475 yield current_run
476 current_run = []
477
478 def test_subinterps_main(self):
479 for run in self.run_repeated_init_and_subinterpreters():
480 main = run[0]
481
482 self.assertEqual(main.id, '0')
483
484 def test_subinterps_different_ids(self):
485 for run in self.run_repeated_init_and_subinterpreters():
486 main, *subs, _ = run
487
488 mainid = int(main.id)
489 for i, sub in enumerate(subs):
490 self.assertEqual(sub.id, str(mainid + i + 1))
491
492 def test_subinterps_distinct_state(self):
493 for run in self.run_repeated_init_and_subinterpreters():
494 main, *subs, _ = run
495
496 if '0x0' in main:
497 # XXX Fix on Windows (and other platforms): something
498 # is going on with the pointers in Programs/_testembed.c.
499 # interp.interp is 0x0 and interp.modules is the same
500 # between interpreters.
501 raise unittest.SkipTest('platform prints pointers as 0x0')
502
503 for sub in subs:
Eric Snowe3774162017-05-22 19:46:40 -0700504 # A new subinterpreter may have the same
505 # PyInterpreterState pointer as a previous one if
506 # the earlier one has already been destroyed. So
507 # we compare with the main interpreter. The same
508 # applies to tstate.
Eric Snowd1c3c132017-05-24 17:19:47 -0700509 self.assertNotEqual(sub.interp, main.interp)
510 self.assertNotEqual(sub.tstate, main.tstate)
511 self.assertNotEqual(sub.modules, main.modules)
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000512
513 def test_forced_io_encoding(self):
514 # Checks forced configuration of embedded interpreter IO streams
Victor Stinnereb52ac82017-06-13 11:49:44 +0200515 env = dict(os.environ, PYTHONIOENCODING="utf-8:surrogateescape")
Nick Coghlan6ea41862017-06-11 13:16:15 +1000516 out, err = self.run_embedded_interpreter("forced_io_encoding", env=env)
517 if support.verbose > 1:
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000518 print()
519 print(out)
520 print(err)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000521 expected_stream_encoding = "utf-8"
522 expected_errors = "surrogateescape"
Steve Dower86e9deb2014-11-01 15:11:05 -0700523 expected_output = '\n'.join([
Nick Coghlan4e641df2013-11-03 16:54:46 +1000524 "--- Use defaults ---",
525 "Expected encoding: default",
526 "Expected errors: default",
Victor Stinnerb2bef622014-03-18 02:38:12 +0100527 "stdin: {in_encoding}:{errors}",
528 "stdout: {out_encoding}:{errors}",
529 "stderr: {out_encoding}:backslashreplace",
Nick Coghlan4e641df2013-11-03 16:54:46 +1000530 "--- Set errors only ---",
531 "Expected encoding: default",
Victor Stinnerb2bef622014-03-18 02:38:12 +0100532 "Expected errors: ignore",
533 "stdin: {in_encoding}:ignore",
534 "stdout: {out_encoding}:ignore",
535 "stderr: {out_encoding}:backslashreplace",
Nick Coghlan4e641df2013-11-03 16:54:46 +1000536 "--- Set encoding only ---",
537 "Expected encoding: latin-1",
538 "Expected errors: default",
Victor Stinnerb2bef622014-03-18 02:38:12 +0100539 "stdin: latin-1:{errors}",
540 "stdout: latin-1:{errors}",
Nick Coghlan4e641df2013-11-03 16:54:46 +1000541 "stderr: latin-1:backslashreplace",
542 "--- Set encoding and errors ---",
543 "Expected encoding: latin-1",
Victor Stinnerb2bef622014-03-18 02:38:12 +0100544 "Expected errors: replace",
545 "stdin: latin-1:replace",
546 "stdout: latin-1:replace",
547 "stderr: latin-1:backslashreplace"])
548 expected_output = expected_output.format(
Nick Coghlan6ea41862017-06-11 13:16:15 +1000549 in_encoding=expected_stream_encoding,
550 out_encoding=expected_stream_encoding,
Victor Stinnerb2bef622014-03-18 02:38:12 +0100551 errors=expected_errors)
Nick Coghlan3321fb82013-10-18 23:59:58 +1000552 # This is useful if we ever trip over odd platform behaviour
Nick Coghlan6508dc52013-10-18 01:44:22 +1000553 self.maxDiff = None
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000554 self.assertEqual(out.strip(), expected_output)
Antoine Pitrou8e605772011-04-25 21:21:07 +0200555
Victor Stinnerc4aec362016-03-14 22:26:53 +0100556
Larry Hastings8f904da2012-06-22 03:56:29 -0700557class SkipitemTest(unittest.TestCase):
558
559 def test_skipitem(self):
560 """
561 If this test failed, you probably added a new "format unit"
562 in Python/getargs.c, but neglected to update our poor friend
563 skipitem() in the same file. (If so, shame on you!)
564
Larry Hastings48ed3602012-06-22 12:58:36 -0700565 With a few exceptions**, this function brute-force tests all
566 printable ASCII*** characters (32 to 126 inclusive) as format units,
567 checking to see that PyArg_ParseTupleAndKeywords() return consistent
568 errors both when the unit is attempted to be used and when it is
569 skipped. If the format unit doesn't exist, we'll get one of two
570 specific error messages (one for used, one for skipped); if it does
571 exist we *won't* get that error--we'll get either no error or some
572 other error. If we get the specific "does not exist" error for one
573 test and not for the other, there's a mismatch, and the test fails.
Larry Hastings8f904da2012-06-22 03:56:29 -0700574
Larry Hastings48ed3602012-06-22 12:58:36 -0700575 ** Some format units have special funny semantics and it would
Martin Panter46f50722016-05-26 05:35:26 +0000576 be difficult to accommodate them here. Since these are all
Larry Hastings48ed3602012-06-22 12:58:36 -0700577 well-established and properly skipped in skipitem() we can
578 get away with not testing them--this test is really intended
579 to catch *new* format units.
580
581 *** Python C source files must be ASCII. Therefore it's impossible
582 to have non-ASCII format units.
583
Larry Hastings8f904da2012-06-22 03:56:29 -0700584 """
585 empty_tuple = ()
586 tuple_1 = (0,)
587 dict_b = {'b':1}
588 keywords = ["a", "b"]
589
Larry Hastings48ed3602012-06-22 12:58:36 -0700590 for i in range(32, 127):
Larry Hastings8f904da2012-06-22 03:56:29 -0700591 c = chr(i)
592
Larry Hastings8f904da2012-06-22 03:56:29 -0700593 # skip parentheses, the error reporting is inconsistent about them
594 # skip 'e', it's always a two-character code
595 # skip '|' and '$', they don't represent arguments anyway
Larry Hastings48ed3602012-06-22 12:58:36 -0700596 if c in '()e|$':
Larry Hastings8f904da2012-06-22 03:56:29 -0700597 continue
598
599 # test the format unit when not skipped
600 format = c + "i"
601 try:
Larry Hastings8f904da2012-06-22 03:56:29 -0700602 _testcapi.parse_tuple_and_keywords(tuple_1, dict_b,
Serhiy Storchaka5f161fd2017-05-04 00:03:23 +0300603 format, keywords)
Larry Hastings8f904da2012-06-22 03:56:29 -0700604 when_not_skipped = False
Serhiy Storchaka4cd63ef2016-02-08 01:22:47 +0200605 except SystemError as e:
Serhiy Storchakac4b813d2016-02-08 01:06:11 +0200606 s = "argument 1 (impossible<bad format char>)"
Larry Hastings8f904da2012-06-22 03:56:29 -0700607 when_not_skipped = (str(e) == s)
Serhiy Storchakaa9725f82016-02-11 12:41:40 +0200608 except TypeError:
Larry Hastings8f904da2012-06-22 03:56:29 -0700609 when_not_skipped = False
610
611 # test the format unit when skipped
612 optional_format = "|" + format
613 try:
614 _testcapi.parse_tuple_and_keywords(empty_tuple, dict_b,
Serhiy Storchaka5f161fd2017-05-04 00:03:23 +0300615 optional_format, keywords)
Larry Hastings8f904da2012-06-22 03:56:29 -0700616 when_skipped = False
Serhiy Storchakaa9725f82016-02-11 12:41:40 +0200617 except SystemError as e:
Larry Hastings8f904da2012-06-22 03:56:29 -0700618 s = "impossible<bad format char>: '{}'".format(format)
619 when_skipped = (str(e) == s)
620
621 message = ("test_skipitem_parity: "
622 "detected mismatch between convertsimple and skipitem "
623 "for format unit '{}' ({}), not skipped {}, skipped {}".format(
624 c, i, when_skipped, when_not_skipped))
625 self.assertIs(when_skipped, when_not_skipped, message)
Antoine Pitrou8e605772011-04-25 21:21:07 +0200626
Jesus Cea6e1d2b62012-10-04 16:06:30 +0200627 def test_parse_tuple_and_keywords(self):
Serhiy Storchaka5f161fd2017-05-04 00:03:23 +0300628 # Test handling errors in the parse_tuple_and_keywords helper itself
Jesus Cea6e1d2b62012-10-04 16:06:30 +0200629 self.assertRaises(TypeError, _testcapi.parse_tuple_and_keywords,
630 (), {}, 42, [])
631 self.assertRaises(ValueError, _testcapi.parse_tuple_and_keywords,
Serhiy Storchaka5f161fd2017-05-04 00:03:23 +0300632 (), {}, '', 42)
Jesus Cea6e1d2b62012-10-04 16:06:30 +0200633 self.assertRaises(ValueError, _testcapi.parse_tuple_and_keywords,
Serhiy Storchaka5f161fd2017-05-04 00:03:23 +0300634 (), {}, '', [''] * 42)
Jesus Cea6e1d2b62012-10-04 16:06:30 +0200635 self.assertRaises(ValueError, _testcapi.parse_tuple_and_keywords,
Serhiy Storchaka5f161fd2017-05-04 00:03:23 +0300636 (), {}, '', [42])
637
638 def test_bad_use(self):
639 # Test handling invalid format and keywords in
640 # PyArg_ParseTupleAndKeywords()
641 self.assertRaises(SystemError, _testcapi.parse_tuple_and_keywords,
642 (1,), {}, '||O', ['a'])
643 self.assertRaises(SystemError, _testcapi.parse_tuple_and_keywords,
644 (1, 2), {}, '|O|O', ['a', 'b'])
645 self.assertRaises(SystemError, _testcapi.parse_tuple_and_keywords,
646 (), {'a': 1}, '$$O', ['a'])
647 self.assertRaises(SystemError, _testcapi.parse_tuple_and_keywords,
648 (), {'a': 1, 'b': 2}, '$O$O', ['a', 'b'])
649 self.assertRaises(SystemError, _testcapi.parse_tuple_and_keywords,
650 (), {'a': 1}, '$|O', ['a'])
651 self.assertRaises(SystemError, _testcapi.parse_tuple_and_keywords,
652 (), {'a': 1, 'b': 2}, '$O|O', ['a', 'b'])
653 self.assertRaises(SystemError, _testcapi.parse_tuple_and_keywords,
654 (1,), {}, '|O', ['a', 'b'])
655 self.assertRaises(SystemError, _testcapi.parse_tuple_and_keywords,
656 (1,), {}, '|OO', ['a'])
657 self.assertRaises(SystemError, _testcapi.parse_tuple_and_keywords,
658 (), {}, '|$O', [''])
659 self.assertRaises(SystemError, _testcapi.parse_tuple_and_keywords,
660 (), {}, '|OO', ['a', ''])
Jesus Cea6e1d2b62012-10-04 16:06:30 +0200661
Serhiy Storchakaf41b82f2016-06-09 16:30:29 +0300662 def test_positional_only(self):
663 parse = _testcapi.parse_tuple_and_keywords
664
Serhiy Storchaka5f161fd2017-05-04 00:03:23 +0300665 parse((1, 2, 3), {}, 'OOO', ['', '', 'a'])
666 parse((1, 2), {'a': 3}, 'OOO', ['', '', 'a'])
Serhiy Storchakaf41b82f2016-06-09 16:30:29 +0300667 with self.assertRaisesRegex(TypeError,
Michael Seifert64c8f702017-04-09 09:47:12 +0200668 r'function takes at least 2 positional arguments \(1 given\)'):
Serhiy Storchaka5f161fd2017-05-04 00:03:23 +0300669 parse((1,), {'a': 3}, 'OOO', ['', '', 'a'])
670 parse((1,), {}, 'O|OO', ['', '', 'a'])
Serhiy Storchakaf41b82f2016-06-09 16:30:29 +0300671 with self.assertRaisesRegex(TypeError,
Michael Seifert64c8f702017-04-09 09:47:12 +0200672 r'function takes at least 1 positional arguments \(0 given\)'):
Serhiy Storchaka5f161fd2017-05-04 00:03:23 +0300673 parse((), {}, 'O|OO', ['', '', 'a'])
674 parse((1, 2), {'a': 3}, 'OO$O', ['', '', 'a'])
Serhiy Storchakaf41b82f2016-06-09 16:30:29 +0300675 with self.assertRaisesRegex(TypeError,
Michael Seifert64c8f702017-04-09 09:47:12 +0200676 r'function takes exactly 2 positional arguments \(1 given\)'):
Serhiy Storchaka5f161fd2017-05-04 00:03:23 +0300677 parse((1,), {'a': 3}, 'OO$O', ['', '', 'a'])
678 parse((1,), {}, 'O|O$O', ['', '', 'a'])
Serhiy Storchakaf41b82f2016-06-09 16:30:29 +0300679 with self.assertRaisesRegex(TypeError,
Michael Seifert64c8f702017-04-09 09:47:12 +0200680 r'function takes at least 1 positional arguments \(0 given\)'):
Serhiy Storchaka5f161fd2017-05-04 00:03:23 +0300681 parse((), {}, 'O|O$O', ['', '', 'a'])
R David Murray44b548d2016-09-08 13:59:53 -0400682 with self.assertRaisesRegex(SystemError, r'Empty parameter name after \$'):
Serhiy Storchaka5f161fd2017-05-04 00:03:23 +0300683 parse((1,), {}, 'O|$OO', ['', '', 'a'])
Serhiy Storchakaf41b82f2016-06-09 16:30:29 +0300684 with self.assertRaisesRegex(SystemError, 'Empty keyword'):
Serhiy Storchaka5f161fd2017-05-04 00:03:23 +0300685 parse((1,), {}, 'O|OO', ['', 'a', ''])
Serhiy Storchakaf41b82f2016-06-09 16:30:29 +0300686
Victor Stinner34be8072016-03-14 12:04:26 +0100687
Ezio Melotti29267c82013-02-23 05:52:46 +0200688@unittest.skipUnless(threading, 'Threading required for this test.')
689class TestThreadState(unittest.TestCase):
690
691 @support.reap_threads
692 def test_thread_state(self):
693 # some extra thread-state tests driven via _testcapi
694 def target():
695 idents = []
696
697 def callback():
Ezio Melotti35246bd2013-02-23 05:58:38 +0200698 idents.append(threading.get_ident())
Ezio Melotti29267c82013-02-23 05:52:46 +0200699
700 _testcapi._test_thread_state(callback)
701 a = b = callback
702 time.sleep(1)
703 # Check our main thread is in the list exactly 3 times.
Ezio Melotti35246bd2013-02-23 05:58:38 +0200704 self.assertEqual(idents.count(threading.get_ident()), 3,
Ezio Melotti29267c82013-02-23 05:52:46 +0200705 "Couldn't find main thread correctly in the list")
706
707 target()
708 t = threading.Thread(target=target)
709 t.start()
710 t.join()
711
Victor Stinner34be8072016-03-14 12:04:26 +0100712
Zachary Warec12f09e2013-11-11 22:47:04 -0600713class Test_testcapi(unittest.TestCase):
714 def test__testcapi(self):
715 for name in dir(_testcapi):
716 if name.startswith('test_'):
Zachary Waredfcd6942013-11-11 22:59:23 -0600717 with self.subTest("internal", name=name):
718 test = getattr(_testcapi, name)
719 test()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000720
Victor Stinner34be8072016-03-14 12:04:26 +0100721
Victor Stinnerc4aec362016-03-14 22:26:53 +0100722class PyMemDebugTests(unittest.TestCase):
723 PYTHONMALLOC = 'debug'
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100724 # '0x04c06e0' or '04C06E0'
Victor Stinner08572f62016-03-14 21:55:43 +0100725 PTR_REGEX = r'(?:0x)?[0-9a-fA-F]+'
Victor Stinner34be8072016-03-14 12:04:26 +0100726
727 def check(self, code):
728 with support.SuppressCrashReport():
Victor Stinnerc4aec362016-03-14 22:26:53 +0100729 out = assert_python_failure('-c', code,
730 PYTHONMALLOC=self.PYTHONMALLOC)
Victor Stinner34be8072016-03-14 12:04:26 +0100731 stderr = out.err
732 return stderr.decode('ascii', 'replace')
733
734 def test_buffer_overflow(self):
735 out = self.check('import _testcapi; _testcapi.pymem_buffer_overflow()')
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100736 regex = (r"Debug memory block at address p={ptr}: API 'm'\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100737 r" 16 bytes originally requested\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100738 r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n"
739 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 +0100740 r" at tail\+0: 0x78 \*\*\* OUCH\n"
741 r" at tail\+1: 0xfb\n"
742 r" at tail\+2: 0xfb\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100743 r" .*\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100744 r" The block was made by call #[0-9]+ to debug malloc/realloc.\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100745 r" Data at p: cb cb cb .*\n"
Victor Stinner6453e9e2016-03-15 23:36:28 +0100746 r"\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100747 r"Fatal Python error: bad trailing pad byte")
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100748 regex = regex.format(ptr=self.PTR_REGEX)
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100749 regex = re.compile(regex, flags=re.DOTALL)
Victor Stinner34be8072016-03-14 12:04:26 +0100750 self.assertRegex(out, regex)
751
752 def test_api_misuse(self):
753 out = self.check('import _testcapi; _testcapi.pymem_api_misuse()')
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100754 regex = (r"Debug memory block at address p={ptr}: API 'm'\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100755 r" 16 bytes originally requested\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100756 r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n"
757 r" The [0-9] pad bytes at tail={ptr} are FORBIDDENBYTE, as expected.\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100758 r" The block was made by call #[0-9]+ to debug malloc/realloc.\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100759 r" Data at p: cb cb cb .*\n"
Victor Stinner6453e9e2016-03-15 23:36:28 +0100760 r"\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100761 r"Fatal Python error: bad ID: Allocated using API 'm', verified using API 'r'\n")
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100762 regex = regex.format(ptr=self.PTR_REGEX)
Victor Stinner34be8072016-03-14 12:04:26 +0100763 self.assertRegex(out, regex)
764
Martin Panter56b2cf52016-10-20 21:45:49 +0000765 @unittest.skipUnless(threading, 'Test requires a GIL (multithreading)')
Victor Stinnerad524372016-03-16 12:12:53 +0100766 def check_malloc_without_gil(self, code):
Victor Stinnerc4aec362016-03-14 22:26:53 +0100767 out = self.check(code)
768 expected = ('Fatal Python error: Python memory allocator called '
769 'without holding the GIL')
770 self.assertIn(expected, out)
Victor Stinner34be8072016-03-14 12:04:26 +0100771
Victor Stinnerad524372016-03-16 12:12:53 +0100772 def test_pymem_malloc_without_gil(self):
773 # Debug hooks must raise an error if PyMem_Malloc() is called
774 # without holding the GIL
775 code = 'import _testcapi; _testcapi.pymem_malloc_without_gil()'
776 self.check_malloc_without_gil(code)
777
778 def test_pyobject_malloc_without_gil(self):
779 # Debug hooks must raise an error if PyObject_Malloc() is called
780 # without holding the GIL
781 code = 'import _testcapi; _testcapi.pyobject_malloc_without_gil()'
782 self.check_malloc_without_gil(code)
783
Victor Stinnerc4aec362016-03-14 22:26:53 +0100784
785class PyMemMallocDebugTests(PyMemDebugTests):
786 PYTHONMALLOC = 'malloc_debug'
Victor Stinner34be8072016-03-14 12:04:26 +0100787
788
789@unittest.skipUnless(sysconfig.get_config_var('WITH_PYMALLOC') == 1,
790 'need pymalloc')
Victor Stinnerc4aec362016-03-14 22:26:53 +0100791class PyMemPymallocDebugTests(PyMemDebugTests):
792 PYTHONMALLOC = 'pymalloc_debug'
Victor Stinner34be8072016-03-14 12:04:26 +0100793
794
795@unittest.skipUnless(Py_DEBUG, 'need Py_DEBUG')
Victor Stinnerc4aec362016-03-14 22:26:53 +0100796class PyMemDefaultTests(PyMemDebugTests):
797 # test default allocator of Python compiled in debug mode
798 PYTHONMALLOC = ''
Victor Stinner34be8072016-03-14 12:04:26 +0100799
800
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000801if __name__ == "__main__":
Zachary Warec12f09e2013-11-11 22:47:04 -0600802 unittest.main()