blob: bb5b2a3b9f0d73402f8320859fef0ae7591a56f2 [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
Oren Milman0ccc0f62017-10-08 11:17:46 +03004from collections import namedtuple, OrderedDict
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
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020014import threading
Benjamin Petersona54c9092009-01-13 02:11:23 +000015import time
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000016import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +000017from test import support
Larry Hastingsfcafe432013-11-23 17:35:48 -080018from test.support import MISSING_C_DOCSTRINGS
xdegaye85f64302017-07-01 14:14:45 +020019from test.support.script_helper import assert_python_failure, assert_python_ok
Victor Stinner45df8202010-04-28 22:31:17 +000020try:
Stefan Krahfd24f9e2012-08-20 11:04:24 +020021 import _posixsubprocess
22except ImportError:
23 _posixsubprocess = None
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020024
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +020025# Skip this test if the _testcapi module isn't available.
26_testcapi = support.import_module('_testcapi')
Tim Peters9ea17ac2001-02-02 05:57:15 +000027
Victor Stinnerefde1462015-03-21 15:04:43 +010028# Were we compiled --with-pydebug or with #define Py_DEBUG?
29Py_DEBUG = hasattr(sys, 'gettotalrefcount')
30
Benjamin Petersona54c9092009-01-13 02:11:23 +000031
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000032def testfunction(self):
33 """some doc"""
34 return self
35
36class InstanceMethod:
37 id = _testcapi.instancemethod(id)
38 testfunction = _testcapi.instancemethod(testfunction)
39
40class CAPITest(unittest.TestCase):
41
42 def test_instancemethod(self):
43 inst = InstanceMethod()
44 self.assertEqual(id(inst), inst.id())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000045 self.assertTrue(inst.testfunction() is inst)
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000046 self.assertEqual(inst.testfunction.__doc__, testfunction.__doc__)
47 self.assertEqual(InstanceMethod.testfunction.__doc__, testfunction.__doc__)
48
49 InstanceMethod.testfunction.attribute = "test"
50 self.assertEqual(testfunction.attribute, "test")
51 self.assertRaises(AttributeError, setattr, inst.testfunction, "attribute", "test")
52
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000053 def test_no_FatalError_infinite_loop(self):
Antoine Pitrou77e904e2013-10-08 23:04:32 +020054 with support.SuppressCrashReport():
Ezio Melotti25a40452013-03-05 20:26:17 +020055 p = subprocess.Popen([sys.executable, "-c",
Ezio Melottie1857d92013-03-05 20:31:34 +020056 'import _testcapi;'
57 '_testcapi.crash_no_current_thread()'],
58 stdout=subprocess.PIPE,
59 stderr=subprocess.PIPE)
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000060 (out, err) = p.communicate()
61 self.assertEqual(out, b'')
62 # This used to cause an infinite loop.
Vinay Sajip73954042012-05-06 11:34:50 +010063 self.assertTrue(err.rstrip().startswith(
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000064 b'Fatal Python error:'
Vinay Sajip73954042012-05-06 11:34:50 +010065 b' PyThreadState_Get: no current thread'))
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000066
Antoine Pitrou915605c2011-02-24 20:53:48 +000067 def test_memoryview_from_NULL_pointer(self):
68 self.assertRaises(ValueError, _testcapi.make_memoryview_from_NULL_pointer)
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000069
Martin v. Löwisaa2efcb2012-04-19 14:33:43 +020070 def test_exc_info(self):
71 raised_exception = ValueError("5")
72 new_exc = TypeError("TEST")
73 try:
74 raise raised_exception
75 except ValueError as e:
76 tb = e.__traceback__
77 orig_sys_exc_info = sys.exc_info()
78 orig_exc_info = _testcapi.set_exc_info(new_exc.__class__, new_exc, None)
79 new_sys_exc_info = sys.exc_info()
80 new_exc_info = _testcapi.set_exc_info(*orig_exc_info)
81 reset_sys_exc_info = sys.exc_info()
82
83 self.assertEqual(orig_exc_info[1], e)
84
85 self.assertSequenceEqual(orig_exc_info, (raised_exception.__class__, raised_exception, tb))
86 self.assertSequenceEqual(orig_sys_exc_info, orig_exc_info)
87 self.assertSequenceEqual(reset_sys_exc_info, orig_exc_info)
88 self.assertSequenceEqual(new_exc_info, (new_exc.__class__, new_exc, None))
89 self.assertSequenceEqual(new_sys_exc_info, new_exc_info)
90 else:
91 self.assertTrue(False)
92
Stefan Krahfd24f9e2012-08-20 11:04:24 +020093 @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
94 def test_seq_bytes_to_charp_array(self):
95 # Issue #15732: crash in _PySequence_BytesToCharpArray()
96 class Z(object):
97 def __len__(self):
98 return 1
99 self.assertRaises(TypeError, _posixsubprocess.fork_exec,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300100 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 +0200101 # Issue #15736: overflow in _PySequence_BytesToCharpArray()
102 class Z(object):
103 def __len__(self):
104 return sys.maxsize
105 def __getitem__(self, i):
106 return b'x'
107 self.assertRaises(MemoryError, _posixsubprocess.fork_exec,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300108 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 +0200109
Stefan Krahdb579d72012-08-20 14:36:47 +0200110 @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
111 def test_subprocess_fork_exec(self):
112 class Z(object):
113 def __len__(self):
114 return 1
115
116 # Issue #15738: crash in subprocess_fork_exec()
117 self.assertRaises(TypeError, _posixsubprocess.fork_exec,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +0300118 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 +0200119
Larry Hastingsfcafe432013-11-23 17:35:48 -0800120 @unittest.skipIf(MISSING_C_DOCSTRINGS,
121 "Signature information for builtins requires docstrings")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800122 def test_docstring_signature_parsing(self):
123
124 self.assertEqual(_testcapi.no_docstring.__doc__, None)
125 self.assertEqual(_testcapi.no_docstring.__text_signature__, None)
126
Zachary Ware8ef887c2015-04-13 18:22:35 -0500127 self.assertEqual(_testcapi.docstring_empty.__doc__, None)
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800128 self.assertEqual(_testcapi.docstring_empty.__text_signature__, None)
129
130 self.assertEqual(_testcapi.docstring_no_signature.__doc__,
131 "This docstring has no signature.")
132 self.assertEqual(_testcapi.docstring_no_signature.__text_signature__, None)
133
134 self.assertEqual(_testcapi.docstring_with_invalid_signature.__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800135 "docstring_with_invalid_signature($module, /, boo)\n"
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800136 "\n"
137 "This docstring has an invalid signature."
138 )
139 self.assertEqual(_testcapi.docstring_with_invalid_signature.__text_signature__, None)
140
Larry Hastings2623c8c2014-02-08 22:15:29 -0800141 self.assertEqual(_testcapi.docstring_with_invalid_signature2.__doc__,
142 "docstring_with_invalid_signature2($module, /, boo)\n"
143 "\n"
144 "--\n"
145 "\n"
146 "This docstring also has an invalid signature."
147 )
148 self.assertEqual(_testcapi.docstring_with_invalid_signature2.__text_signature__, None)
149
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800150 self.assertEqual(_testcapi.docstring_with_signature.__doc__,
151 "This docstring has a valid signature.")
Larry Hastings2623c8c2014-02-08 22:15:29 -0800152 self.assertEqual(_testcapi.docstring_with_signature.__text_signature__, "($module, /, sig)")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800153
Zachary Ware8ef887c2015-04-13 18:22:35 -0500154 self.assertEqual(_testcapi.docstring_with_signature_but_no_doc.__doc__, None)
155 self.assertEqual(_testcapi.docstring_with_signature_but_no_doc.__text_signature__,
156 "($module, /, sig)")
157
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800158 self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800159 "\nThis docstring has a valid signature and some extra newlines.")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800160 self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__text_signature__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800161 "($module, /, parameter)")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800162
Benjamin Petersond51374e2014-04-09 23:55:56 -0400163 def test_c_type_with_matrix_multiplication(self):
164 M = _testcapi.matmulType
165 m1 = M()
166 m2 = M()
167 self.assertEqual(m1 @ m2, ("matmul", m1, m2))
168 self.assertEqual(m1 @ 42, ("matmul", m1, 42))
169 self.assertEqual(42 @ m1, ("matmul", 42, m1))
170 o = m1
171 o @= m2
172 self.assertEqual(o, ("imatmul", m1, m2))
173 o = m1
174 o @= 42
175 self.assertEqual(o, ("imatmul", m1, 42))
176 o = 42
177 o @= m1
178 self.assertEqual(o, ("matmul", 42, m1))
179
Victor Stinnerefde1462015-03-21 15:04:43 +0100180 def test_return_null_without_error(self):
181 # Issue #23571: A function must not return NULL without setting an
182 # error
183 if Py_DEBUG:
184 code = textwrap.dedent("""
185 import _testcapi
186 from test import support
187
188 with support.SuppressCrashReport():
189 _testcapi.return_null_without_error()
190 """)
191 rc, out, err = assert_python_failure('-c', code)
Victor Stinner381a9bc2015-03-24 14:01:32 +0100192 self.assertRegex(err.replace(b'\r', b''),
Victor Stinner944fbcc2015-03-24 16:28:52 +0100193 br'Fatal Python error: a function returned NULL '
194 br'without setting an error\n'
Victor Stinner381a9bc2015-03-24 14:01:32 +0100195 br'SystemError: <built-in function '
196 br'return_null_without_error> returned NULL '
197 br'without setting an error\n'
198 br'\n'
199 br'Current thread.*:\n'
200 br' File .*", line 6 in <module>')
Victor Stinnerefde1462015-03-21 15:04:43 +0100201 else:
202 with self.assertRaises(SystemError) as cm:
203 _testcapi.return_null_without_error()
204 self.assertRegex(str(cm.exception),
205 'return_null_without_error.* '
206 'returned NULL without setting an error')
207
208 def test_return_result_with_error(self):
209 # Issue #23571: A function must not return a result with an error set
210 if Py_DEBUG:
211 code = textwrap.dedent("""
212 import _testcapi
213 from test import support
214
215 with support.SuppressCrashReport():
216 _testcapi.return_result_with_error()
217 """)
218 rc, out, err = assert_python_failure('-c', code)
Victor Stinner381a9bc2015-03-24 14:01:32 +0100219 self.assertRegex(err.replace(b'\r', b''),
Victor Stinner944fbcc2015-03-24 16:28:52 +0100220 br'Fatal Python error: a function returned a '
221 br'result with an error set\n'
Victor Stinner381a9bc2015-03-24 14:01:32 +0100222 br'ValueError\n'
223 br'\n'
Serhiy Storchaka467ab192016-10-21 17:09:17 +0300224 br'The above exception was the direct cause '
225 br'of the following exception:\n'
Victor Stinner381a9bc2015-03-24 14:01:32 +0100226 br'\n'
227 br'SystemError: <built-in '
228 br'function return_result_with_error> '
229 br'returned a result with an error set\n'
230 br'\n'
231 br'Current thread.*:\n'
232 br' File .*, line 6 in <module>')
Victor Stinnerefde1462015-03-21 15:04:43 +0100233 else:
234 with self.assertRaises(SystemError) as cm:
235 _testcapi.return_result_with_error()
236 self.assertRegex(str(cm.exception),
237 'return_result_with_error.* '
238 'returned a result with an error set')
239
Serhiy Storchaka13e602e2016-05-20 22:31:14 +0300240 def test_buildvalue_N(self):
241 _testcapi.test_buildvalue_N()
242
xdegaye85f64302017-07-01 14:14:45 +0200243 def test_set_nomemory(self):
244 code = """if 1:
245 import _testcapi
246
247 class C(): pass
248
249 # The first loop tests both functions and that remove_mem_hooks()
250 # can be called twice in a row. The second loop checks a call to
251 # set_nomemory() after a call to remove_mem_hooks(). The third
252 # loop checks the start and stop arguments of set_nomemory().
253 for outer_cnt in range(1, 4):
254 start = 10 * outer_cnt
255 for j in range(100):
256 if j == 0:
257 if outer_cnt != 3:
258 _testcapi.set_nomemory(start)
259 else:
260 _testcapi.set_nomemory(start, start + 1)
261 try:
262 C()
263 except MemoryError as e:
264 if outer_cnt != 3:
265 _testcapi.remove_mem_hooks()
266 print('MemoryError', outer_cnt, j)
267 _testcapi.remove_mem_hooks()
268 break
269 """
270 rc, out, err = assert_python_ok('-c', code)
271 self.assertIn(b'MemoryError 1 10', out)
272 self.assertIn(b'MemoryError 2 20', out)
273 self.assertIn(b'MemoryError 3 30', out)
274
Oren Milman0ccc0f62017-10-08 11:17:46 +0300275 def test_mapping_keys_values_items(self):
276 class Mapping1(dict):
277 def keys(self):
278 return list(super().keys())
279 def values(self):
280 return list(super().values())
281 def items(self):
282 return list(super().items())
283 class Mapping2(dict):
284 def keys(self):
285 return tuple(super().keys())
286 def values(self):
287 return tuple(super().values())
288 def items(self):
289 return tuple(super().items())
290 dict_obj = {'foo': 1, 'bar': 2, 'spam': 3}
291
292 for mapping in [{}, OrderedDict(), Mapping1(), Mapping2(),
293 dict_obj, OrderedDict(dict_obj),
294 Mapping1(dict_obj), Mapping2(dict_obj)]:
295 self.assertListEqual(_testcapi.get_mapping_keys(mapping),
296 list(mapping.keys()))
297 self.assertListEqual(_testcapi.get_mapping_values(mapping),
298 list(mapping.values()))
299 self.assertListEqual(_testcapi.get_mapping_items(mapping),
300 list(mapping.items()))
301
302 def test_mapping_keys_values_items_bad_arg(self):
303 self.assertRaises(AttributeError, _testcapi.get_mapping_keys, None)
304 self.assertRaises(AttributeError, _testcapi.get_mapping_values, None)
305 self.assertRaises(AttributeError, _testcapi.get_mapping_items, None)
306
307 class BadMapping:
308 def keys(self):
309 return None
310 def values(self):
311 return None
312 def items(self):
313 return None
314 bad_mapping = BadMapping()
315 self.assertRaises(TypeError, _testcapi.get_mapping_keys, bad_mapping)
316 self.assertRaises(TypeError, _testcapi.get_mapping_values, bad_mapping)
317 self.assertRaises(TypeError, _testcapi.get_mapping_items, bad_mapping)
318
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800319
Benjamin Petersona54c9092009-01-13 02:11:23 +0000320class TestPendingCalls(unittest.TestCase):
321
322 def pendingcalls_submit(self, l, n):
323 def callback():
324 #this function can be interrupted by thread switching so let's
325 #use an atomic operation
326 l.append(None)
327
328 for i in range(n):
329 time.sleep(random.random()*0.02) #0.01 secs on average
330 #try submitting callback until successful.
331 #rely on regular interrupt to flush queue if we are
332 #unsuccessful.
333 while True:
334 if _testcapi._pending_threadfunc(callback):
335 break;
336
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000337 def pendingcalls_wait(self, l, n, context = None):
Benjamin Petersona54c9092009-01-13 02:11:23 +0000338 #now, stick around until l[0] has grown to 10
339 count = 0;
340 while len(l) != n:
341 #this busy loop is where we expect to be interrupted to
342 #run our callbacks. Note that callbacks are only run on the
343 #main thread
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000344 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +0000345 print("(%i)"%(len(l),),)
346 for i in range(1000):
347 a = i*i
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000348 if context and not context.event.is_set():
349 continue
Benjamin Petersona54c9092009-01-13 02:11:23 +0000350 count += 1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000351 self.assertTrue(count < 10000,
Benjamin Petersona54c9092009-01-13 02:11:23 +0000352 "timeout waiting for %i callbacks, got %i"%(n, len(l)))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000353 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +0000354 print("(%i)"%(len(l),))
355
356 def test_pendingcalls_threaded(self):
Benjamin Petersona54c9092009-01-13 02:11:23 +0000357
358 #do every callback on a separate thread
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000359 n = 32 #total callbacks
Benjamin Petersona54c9092009-01-13 02:11:23 +0000360 threads = []
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000361 class foo(object):pass
362 context = foo()
363 context.l = []
364 context.n = 2 #submits per thread
365 context.nThreads = n // context.n
366 context.nFinished = 0
367 context.lock = threading.Lock()
368 context.event = threading.Event()
369
Serhiy Storchaka263dcd22015-04-01 13:01:14 +0300370 threads = [threading.Thread(target=self.pendingcalls_thread,
371 args=(context,))
372 for i in range(context.nThreads)]
373 with support.start_threads(threads):
374 self.pendingcalls_wait(context.l, n, context)
Benjamin Petersona54c9092009-01-13 02:11:23 +0000375
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000376 def pendingcalls_thread(self, context):
377 try:
378 self.pendingcalls_submit(context.l, context.n)
379 finally:
380 with context.lock:
381 context.nFinished += 1
382 nFinished = context.nFinished
383 if False and support.verbose:
384 print("finished threads: ", nFinished)
385 if nFinished == context.nThreads:
386 context.event.set()
387
Benjamin Petersona54c9092009-01-13 02:11:23 +0000388 def test_pendingcalls_non_threaded(self):
Ezio Melotti13925002011-03-16 11:05:33 +0200389 #again, just using the main thread, likely they will all be dispatched at
Benjamin Petersona54c9092009-01-13 02:11:23 +0000390 #once. It is ok to ask for too many, because we loop until we find a slot.
391 #the loop can be interrupted to dispatch.
392 #there are only 32 dispatch slots, so we go for twice that!
393 l = []
394 n = 64
395 self.pendingcalls_submit(l, n)
396 self.pendingcalls_wait(l, n)
397
Antoine Pitrou7a2572c2013-08-01 20:43:26 +0200398
399class SubinterpreterTest(unittest.TestCase):
400
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100401 def test_subinterps(self):
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100402 import builtins
403 r, w = os.pipe()
404 code = """if 1:
405 import sys, builtins, pickle
406 with open({:d}, "wb") as f:
407 pickle.dump(id(sys.modules), f)
408 pickle.dump(id(builtins), f)
409 """.format(w)
410 with open(r, "rb") as f:
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100411 ret = support.run_in_subinterp(code)
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100412 self.assertEqual(ret, 0)
413 self.assertNotEqual(pickle.load(f), id(sys.modules))
414 self.assertNotEqual(pickle.load(f), id(builtins))
415
Antoine Pitrou7a2572c2013-08-01 20:43:26 +0200416
Martin v. Löwisc15bdef2009-05-29 14:47:46 +0000417# Bug #6012
418class Test6012(unittest.TestCase):
419 def test(self):
420 self.assertEqual(_testcapi.argparsing("Hello", "World"), 1)
Benjamin Petersona54c9092009-01-13 02:11:23 +0000421
Antoine Pitrou8e605772011-04-25 21:21:07 +0200422
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000423class EmbeddingTests(unittest.TestCase):
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000424 def setUp(self):
Zachary Ware6d8a2602015-12-05 00:16:55 -0600425 here = os.path.abspath(__file__)
426 basepath = os.path.dirname(os.path.dirname(os.path.dirname(here)))
Nick Coghlan4e641df2013-11-03 16:54:46 +1000427 exename = "_testembed"
428 if sys.platform.startswith("win"):
429 ext = ("_d" if "_d" in sys.executable else "") + ".exe"
430 exename += ext
431 exepath = os.path.dirname(sys.executable)
432 else:
Nick Coghlanbca9acf2014-09-25 19:48:15 +1000433 exepath = os.path.join(basepath, "Programs")
Nick Coghlan4e641df2013-11-03 16:54:46 +1000434 self.test_exe = exe = os.path.join(exepath, exename)
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000435 if not os.path.exists(exe):
436 self.skipTest("%r doesn't exist" % exe)
Antoine Pitrou8e605772011-04-25 21:21:07 +0200437 # This is needed otherwise we get a fatal error:
438 # "Py_Initialize: Unable to get the locale encoding
439 # LookupError: no codec search functions registered: can't find encoding"
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000440 self.oldcwd = os.getcwd()
Antoine Pitrou8e605772011-04-25 21:21:07 +0200441 os.chdir(basepath)
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000442
443 def tearDown(self):
444 os.chdir(self.oldcwd)
445
Nick Coghlan6ea41862017-06-11 13:16:15 +1000446 def run_embedded_interpreter(self, *args, env=None):
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000447 """Runs a test in the embedded interpreter"""
448 cmd = [self.test_exe]
449 cmd.extend(args)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000450 if env is not None and sys.platform == 'win32':
451 # Windows requires at least the SYSTEMROOT environment variable to
452 # start Python.
453 env = env.copy()
454 env['SYSTEMROOT'] = os.environ['SYSTEMROOT']
455
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000456 p = subprocess.Popen(cmd,
457 stdout=subprocess.PIPE,
Steve Dower86e9deb2014-11-01 15:11:05 -0700458 stderr=subprocess.PIPE,
Nick Coghlan6ea41862017-06-11 13:16:15 +1000459 universal_newlines=True,
460 env=env)
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000461 (out, err) = p.communicate()
462 self.assertEqual(p.returncode, 0,
463 "bad returncode %d, stderr is %r" %
464 (p.returncode, err))
Steve Dower86e9deb2014-11-01 15:11:05 -0700465 return out, err
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000466
Eric Snowd1c3c132017-05-24 17:19:47 -0700467 def run_repeated_init_and_subinterpreters(self):
Steve Dowerea74f0c2017-01-01 20:25:03 -0800468 out, err = self.run_embedded_interpreter("repeated_init_and_subinterpreters")
Eric Snowe3774162017-05-22 19:46:40 -0700469 self.assertEqual(err, "")
470
471 # The output from _testembed looks like this:
472 # --- Pass 0 ---
473 # interp 0 <0x1cf9330>, thread state <0x1cf9700>: id(modules) = 139650431942728
474 # interp 1 <0x1d4f690>, thread state <0x1d35350>: id(modules) = 139650431165784
475 # interp 2 <0x1d5a690>, thread state <0x1d99ed0>: id(modules) = 139650413140368
476 # interp 3 <0x1d4f690>, thread state <0x1dc3340>: id(modules) = 139650412862200
477 # interp 0 <0x1cf9330>, thread state <0x1cf9700>: id(modules) = 139650431942728
478 # --- Pass 1 ---
479 # ...
480
481 interp_pat = (r"^interp (\d+) <(0x[\dA-F]+)>, "
482 r"thread state <(0x[\dA-F]+)>: "
483 r"id\(modules\) = ([\d]+)$")
484 Interp = namedtuple("Interp", "id interp tstate modules")
485
Eric Snowe3774162017-05-22 19:46:40 -0700486 numloops = 0
Eric Snowd1c3c132017-05-24 17:19:47 -0700487 current_run = []
Eric Snowe3774162017-05-22 19:46:40 -0700488 for line in out.splitlines():
489 if line == "--- Pass {} ---".format(numloops):
Eric Snowd1c3c132017-05-24 17:19:47 -0700490 self.assertEqual(len(current_run), 0)
Eric Snowe3774162017-05-22 19:46:40 -0700491 if support.verbose:
492 print(line)
Eric Snowe3774162017-05-22 19:46:40 -0700493 numloops += 1
Eric Snowe3774162017-05-22 19:46:40 -0700494 continue
Eric Snowe3774162017-05-22 19:46:40 -0700495
Eric Snowd1c3c132017-05-24 17:19:47 -0700496 self.assertLess(len(current_run), 5)
Eric Snowe3774162017-05-22 19:46:40 -0700497 match = re.match(interp_pat, line)
498 if match is None:
499 self.assertRegex(line, interp_pat)
500
Eric Snowe3774162017-05-22 19:46:40 -0700501 # Parse the line from the loop. The first line is the main
502 # interpreter and the 3 afterward are subinterpreters.
503 interp = Interp(*match.groups())
504 if support.verbose:
505 print(interp)
Eric Snowe3774162017-05-22 19:46:40 -0700506 self.assertTrue(interp.interp)
507 self.assertTrue(interp.tstate)
508 self.assertTrue(interp.modules)
Eric Snowd1c3c132017-05-24 17:19:47 -0700509 current_run.append(interp)
510
511 # The last line in the loop should be the same as the first.
512 if len(current_run) == 5:
513 main = current_run[0]
514 self.assertEqual(interp, main)
515 yield current_run
516 current_run = []
517
518 def test_subinterps_main(self):
519 for run in self.run_repeated_init_and_subinterpreters():
520 main = run[0]
521
522 self.assertEqual(main.id, '0')
523
524 def test_subinterps_different_ids(self):
525 for run in self.run_repeated_init_and_subinterpreters():
526 main, *subs, _ = run
527
528 mainid = int(main.id)
529 for i, sub in enumerate(subs):
530 self.assertEqual(sub.id, str(mainid + i + 1))
531
532 def test_subinterps_distinct_state(self):
533 for run in self.run_repeated_init_and_subinterpreters():
534 main, *subs, _ = run
535
536 if '0x0' in main:
537 # XXX Fix on Windows (and other platforms): something
538 # is going on with the pointers in Programs/_testembed.c.
539 # interp.interp is 0x0 and interp.modules is the same
540 # between interpreters.
541 raise unittest.SkipTest('platform prints pointers as 0x0')
542
543 for sub in subs:
Eric Snowe3774162017-05-22 19:46:40 -0700544 # A new subinterpreter may have the same
545 # PyInterpreterState pointer as a previous one if
546 # the earlier one has already been destroyed. So
547 # we compare with the main interpreter. The same
548 # applies to tstate.
Eric Snowd1c3c132017-05-24 17:19:47 -0700549 self.assertNotEqual(sub.interp, main.interp)
550 self.assertNotEqual(sub.tstate, main.tstate)
551 self.assertNotEqual(sub.modules, main.modules)
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000552
553 def test_forced_io_encoding(self):
554 # Checks forced configuration of embedded interpreter IO streams
Victor Stinnereb52ac82017-06-13 11:49:44 +0200555 env = dict(os.environ, PYTHONIOENCODING="utf-8:surrogateescape")
Nick Coghlan6ea41862017-06-11 13:16:15 +1000556 out, err = self.run_embedded_interpreter("forced_io_encoding", env=env)
557 if support.verbose > 1:
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000558 print()
559 print(out)
560 print(err)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000561 expected_stream_encoding = "utf-8"
562 expected_errors = "surrogateescape"
Steve Dower86e9deb2014-11-01 15:11:05 -0700563 expected_output = '\n'.join([
Nick Coghlan4e641df2013-11-03 16:54:46 +1000564 "--- Use defaults ---",
565 "Expected encoding: default",
566 "Expected errors: default",
Victor Stinnerb2bef622014-03-18 02:38:12 +0100567 "stdin: {in_encoding}:{errors}",
568 "stdout: {out_encoding}:{errors}",
569 "stderr: {out_encoding}:backslashreplace",
Nick Coghlan4e641df2013-11-03 16:54:46 +1000570 "--- Set errors only ---",
571 "Expected encoding: default",
Victor Stinnerb2bef622014-03-18 02:38:12 +0100572 "Expected errors: ignore",
573 "stdin: {in_encoding}:ignore",
574 "stdout: {out_encoding}:ignore",
575 "stderr: {out_encoding}:backslashreplace",
Nick Coghlan4e641df2013-11-03 16:54:46 +1000576 "--- Set encoding only ---",
577 "Expected encoding: latin-1",
578 "Expected errors: default",
Victor Stinnerb2bef622014-03-18 02:38:12 +0100579 "stdin: latin-1:{errors}",
580 "stdout: latin-1:{errors}",
Nick Coghlan4e641df2013-11-03 16:54:46 +1000581 "stderr: latin-1:backslashreplace",
582 "--- Set encoding and errors ---",
583 "Expected encoding: latin-1",
Victor Stinnerb2bef622014-03-18 02:38:12 +0100584 "Expected errors: replace",
585 "stdin: latin-1:replace",
586 "stdout: latin-1:replace",
587 "stderr: latin-1:backslashreplace"])
588 expected_output = expected_output.format(
Nick Coghlan6ea41862017-06-11 13:16:15 +1000589 in_encoding=expected_stream_encoding,
590 out_encoding=expected_stream_encoding,
Victor Stinnerb2bef622014-03-18 02:38:12 +0100591 errors=expected_errors)
Nick Coghlan3321fb82013-10-18 23:59:58 +1000592 # This is useful if we ever trip over odd platform behaviour
Nick Coghlan6508dc52013-10-18 01:44:22 +1000593 self.maxDiff = None
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000594 self.assertEqual(out.strip(), expected_output)
Antoine Pitrou8e605772011-04-25 21:21:07 +0200595
Victor Stinnerc4aec362016-03-14 22:26:53 +0100596
Larry Hastings8f904da2012-06-22 03:56:29 -0700597class SkipitemTest(unittest.TestCase):
598
599 def test_skipitem(self):
600 """
601 If this test failed, you probably added a new "format unit"
602 in Python/getargs.c, but neglected to update our poor friend
603 skipitem() in the same file. (If so, shame on you!)
604
Larry Hastings48ed3602012-06-22 12:58:36 -0700605 With a few exceptions**, this function brute-force tests all
606 printable ASCII*** characters (32 to 126 inclusive) as format units,
607 checking to see that PyArg_ParseTupleAndKeywords() return consistent
608 errors both when the unit is attempted to be used and when it is
609 skipped. If the format unit doesn't exist, we'll get one of two
610 specific error messages (one for used, one for skipped); if it does
611 exist we *won't* get that error--we'll get either no error or some
612 other error. If we get the specific "does not exist" error for one
613 test and not for the other, there's a mismatch, and the test fails.
Larry Hastings8f904da2012-06-22 03:56:29 -0700614
Larry Hastings48ed3602012-06-22 12:58:36 -0700615 ** Some format units have special funny semantics and it would
Martin Panter46f50722016-05-26 05:35:26 +0000616 be difficult to accommodate them here. Since these are all
Larry Hastings48ed3602012-06-22 12:58:36 -0700617 well-established and properly skipped in skipitem() we can
618 get away with not testing them--this test is really intended
619 to catch *new* format units.
620
621 *** Python C source files must be ASCII. Therefore it's impossible
622 to have non-ASCII format units.
623
Larry Hastings8f904da2012-06-22 03:56:29 -0700624 """
625 empty_tuple = ()
626 tuple_1 = (0,)
627 dict_b = {'b':1}
628 keywords = ["a", "b"]
629
Larry Hastings48ed3602012-06-22 12:58:36 -0700630 for i in range(32, 127):
Larry Hastings8f904da2012-06-22 03:56:29 -0700631 c = chr(i)
632
Larry Hastings8f904da2012-06-22 03:56:29 -0700633 # skip parentheses, the error reporting is inconsistent about them
634 # skip 'e', it's always a two-character code
635 # skip '|' and '$', they don't represent arguments anyway
Larry Hastings48ed3602012-06-22 12:58:36 -0700636 if c in '()e|$':
Larry Hastings8f904da2012-06-22 03:56:29 -0700637 continue
638
639 # test the format unit when not skipped
640 format = c + "i"
641 try:
Larry Hastings8f904da2012-06-22 03:56:29 -0700642 _testcapi.parse_tuple_and_keywords(tuple_1, dict_b,
Serhiy Storchaka5f161fd2017-05-04 00:03:23 +0300643 format, keywords)
Larry Hastings8f904da2012-06-22 03:56:29 -0700644 when_not_skipped = False
Serhiy Storchaka4cd63ef2016-02-08 01:22:47 +0200645 except SystemError as e:
Serhiy Storchakac4b813d2016-02-08 01:06:11 +0200646 s = "argument 1 (impossible<bad format char>)"
Larry Hastings8f904da2012-06-22 03:56:29 -0700647 when_not_skipped = (str(e) == s)
Serhiy Storchakaa9725f82016-02-11 12:41:40 +0200648 except TypeError:
Larry Hastings8f904da2012-06-22 03:56:29 -0700649 when_not_skipped = False
650
651 # test the format unit when skipped
652 optional_format = "|" + format
653 try:
654 _testcapi.parse_tuple_and_keywords(empty_tuple, dict_b,
Serhiy Storchaka5f161fd2017-05-04 00:03:23 +0300655 optional_format, keywords)
Larry Hastings8f904da2012-06-22 03:56:29 -0700656 when_skipped = False
Serhiy Storchakaa9725f82016-02-11 12:41:40 +0200657 except SystemError as e:
Larry Hastings8f904da2012-06-22 03:56:29 -0700658 s = "impossible<bad format char>: '{}'".format(format)
659 when_skipped = (str(e) == s)
660
661 message = ("test_skipitem_parity: "
662 "detected mismatch between convertsimple and skipitem "
663 "for format unit '{}' ({}), not skipped {}, skipped {}".format(
664 c, i, when_skipped, when_not_skipped))
665 self.assertIs(when_skipped, when_not_skipped, message)
Antoine Pitrou8e605772011-04-25 21:21:07 +0200666
Jesus Cea6e1d2b62012-10-04 16:06:30 +0200667 def test_parse_tuple_and_keywords(self):
Serhiy Storchaka5f161fd2017-05-04 00:03:23 +0300668 # Test handling errors in the parse_tuple_and_keywords helper itself
Jesus Cea6e1d2b62012-10-04 16:06:30 +0200669 self.assertRaises(TypeError, _testcapi.parse_tuple_and_keywords,
670 (), {}, 42, [])
671 self.assertRaises(ValueError, _testcapi.parse_tuple_and_keywords,
Serhiy Storchaka5f161fd2017-05-04 00:03:23 +0300672 (), {}, '', 42)
Jesus Cea6e1d2b62012-10-04 16:06:30 +0200673 self.assertRaises(ValueError, _testcapi.parse_tuple_and_keywords,
Serhiy Storchaka5f161fd2017-05-04 00:03:23 +0300674 (), {}, '', [''] * 42)
Jesus Cea6e1d2b62012-10-04 16:06:30 +0200675 self.assertRaises(ValueError, _testcapi.parse_tuple_and_keywords,
Serhiy Storchaka5f161fd2017-05-04 00:03:23 +0300676 (), {}, '', [42])
677
678 def test_bad_use(self):
679 # Test handling invalid format and keywords in
680 # PyArg_ParseTupleAndKeywords()
681 self.assertRaises(SystemError, _testcapi.parse_tuple_and_keywords,
682 (1,), {}, '||O', ['a'])
683 self.assertRaises(SystemError, _testcapi.parse_tuple_and_keywords,
684 (1, 2), {}, '|O|O', ['a', 'b'])
685 self.assertRaises(SystemError, _testcapi.parse_tuple_and_keywords,
686 (), {'a': 1}, '$$O', ['a'])
687 self.assertRaises(SystemError, _testcapi.parse_tuple_and_keywords,
688 (), {'a': 1, 'b': 2}, '$O$O', ['a', 'b'])
689 self.assertRaises(SystemError, _testcapi.parse_tuple_and_keywords,
690 (), {'a': 1}, '$|O', ['a'])
691 self.assertRaises(SystemError, _testcapi.parse_tuple_and_keywords,
692 (), {'a': 1, 'b': 2}, '$O|O', ['a', 'b'])
693 self.assertRaises(SystemError, _testcapi.parse_tuple_and_keywords,
694 (1,), {}, '|O', ['a', 'b'])
695 self.assertRaises(SystemError, _testcapi.parse_tuple_and_keywords,
696 (1,), {}, '|OO', ['a'])
697 self.assertRaises(SystemError, _testcapi.parse_tuple_and_keywords,
698 (), {}, '|$O', [''])
699 self.assertRaises(SystemError, _testcapi.parse_tuple_and_keywords,
700 (), {}, '|OO', ['a', ''])
Jesus Cea6e1d2b62012-10-04 16:06:30 +0200701
Serhiy Storchakaf41b82f2016-06-09 16:30:29 +0300702 def test_positional_only(self):
703 parse = _testcapi.parse_tuple_and_keywords
704
Serhiy Storchaka5f161fd2017-05-04 00:03:23 +0300705 parse((1, 2, 3), {}, 'OOO', ['', '', 'a'])
706 parse((1, 2), {'a': 3}, 'OOO', ['', '', 'a'])
Serhiy Storchakaf41b82f2016-06-09 16:30:29 +0300707 with self.assertRaisesRegex(TypeError,
Michael Seifert64c8f702017-04-09 09:47:12 +0200708 r'function takes at least 2 positional arguments \(1 given\)'):
Serhiy Storchaka5f161fd2017-05-04 00:03:23 +0300709 parse((1,), {'a': 3}, 'OOO', ['', '', 'a'])
710 parse((1,), {}, 'O|OO', ['', '', 'a'])
Serhiy Storchakaf41b82f2016-06-09 16:30:29 +0300711 with self.assertRaisesRegex(TypeError,
Michael Seifert64c8f702017-04-09 09:47:12 +0200712 r'function takes at least 1 positional arguments \(0 given\)'):
Serhiy Storchaka5f161fd2017-05-04 00:03:23 +0300713 parse((), {}, 'O|OO', ['', '', 'a'])
714 parse((1, 2), {'a': 3}, 'OO$O', ['', '', 'a'])
Serhiy Storchakaf41b82f2016-06-09 16:30:29 +0300715 with self.assertRaisesRegex(TypeError,
Michael Seifert64c8f702017-04-09 09:47:12 +0200716 r'function takes exactly 2 positional arguments \(1 given\)'):
Serhiy Storchaka5f161fd2017-05-04 00:03:23 +0300717 parse((1,), {'a': 3}, 'OO$O', ['', '', 'a'])
718 parse((1,), {}, 'O|O$O', ['', '', 'a'])
Serhiy Storchakaf41b82f2016-06-09 16:30:29 +0300719 with self.assertRaisesRegex(TypeError,
Michael Seifert64c8f702017-04-09 09:47:12 +0200720 r'function takes at least 1 positional arguments \(0 given\)'):
Serhiy Storchaka5f161fd2017-05-04 00:03:23 +0300721 parse((), {}, 'O|O$O', ['', '', 'a'])
R David Murray44b548d2016-09-08 13:59:53 -0400722 with self.assertRaisesRegex(SystemError, r'Empty parameter name after \$'):
Serhiy Storchaka5f161fd2017-05-04 00:03:23 +0300723 parse((1,), {}, 'O|$OO', ['', '', 'a'])
Serhiy Storchakaf41b82f2016-06-09 16:30:29 +0300724 with self.assertRaisesRegex(SystemError, 'Empty keyword'):
Serhiy Storchaka5f161fd2017-05-04 00:03:23 +0300725 parse((1,), {}, 'O|OO', ['', 'a', ''])
Serhiy Storchakaf41b82f2016-06-09 16:30:29 +0300726
Victor Stinner34be8072016-03-14 12:04:26 +0100727
Ezio Melotti29267c82013-02-23 05:52:46 +0200728class TestThreadState(unittest.TestCase):
729
730 @support.reap_threads
731 def test_thread_state(self):
732 # some extra thread-state tests driven via _testcapi
733 def target():
734 idents = []
735
736 def callback():
Ezio Melotti35246bd2013-02-23 05:58:38 +0200737 idents.append(threading.get_ident())
Ezio Melotti29267c82013-02-23 05:52:46 +0200738
739 _testcapi._test_thread_state(callback)
740 a = b = callback
741 time.sleep(1)
742 # Check our main thread is in the list exactly 3 times.
Ezio Melotti35246bd2013-02-23 05:58:38 +0200743 self.assertEqual(idents.count(threading.get_ident()), 3,
Ezio Melotti29267c82013-02-23 05:52:46 +0200744 "Couldn't find main thread correctly in the list")
745
746 target()
747 t = threading.Thread(target=target)
748 t.start()
749 t.join()
750
Victor Stinner34be8072016-03-14 12:04:26 +0100751
Zachary Warec12f09e2013-11-11 22:47:04 -0600752class Test_testcapi(unittest.TestCase):
753 def test__testcapi(self):
Victor Stinnere1a470b2017-10-31 08:40:59 -0700754 if support.verbose:
755 print()
Zachary Warec12f09e2013-11-11 22:47:04 -0600756 for name in dir(_testcapi):
Victor Stinnere1a470b2017-10-31 08:40:59 -0700757 if not name.startswith('test_'):
758 continue
759 with self.subTest("internal", name=name):
760 if support.verbose:
761 print(f" {name}", flush=True)
762 test = getattr(_testcapi, name)
763 test()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000764
Victor Stinner34be8072016-03-14 12:04:26 +0100765
Victor Stinnerc4aec362016-03-14 22:26:53 +0100766class PyMemDebugTests(unittest.TestCase):
767 PYTHONMALLOC = 'debug'
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100768 # '0x04c06e0' or '04C06E0'
Victor Stinner08572f62016-03-14 21:55:43 +0100769 PTR_REGEX = r'(?:0x)?[0-9a-fA-F]+'
Victor Stinner34be8072016-03-14 12:04:26 +0100770
771 def check(self, code):
772 with support.SuppressCrashReport():
Victor Stinnerc4aec362016-03-14 22:26:53 +0100773 out = assert_python_failure('-c', code,
774 PYTHONMALLOC=self.PYTHONMALLOC)
Victor Stinner34be8072016-03-14 12:04:26 +0100775 stderr = out.err
776 return stderr.decode('ascii', 'replace')
777
778 def test_buffer_overflow(self):
779 out = self.check('import _testcapi; _testcapi.pymem_buffer_overflow()')
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100780 regex = (r"Debug memory block at address p={ptr}: API 'm'\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100781 r" 16 bytes originally requested\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100782 r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n"
783 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 +0100784 r" at tail\+0: 0x78 \*\*\* OUCH\n"
785 r" at tail\+1: 0xfb\n"
786 r" at tail\+2: 0xfb\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100787 r" .*\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100788 r" The block was made by call #[0-9]+ to debug malloc/realloc.\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100789 r" Data at p: cb cb cb .*\n"
Victor Stinner6453e9e2016-03-15 23:36:28 +0100790 r"\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100791 r"Fatal Python error: bad trailing pad byte")
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100792 regex = regex.format(ptr=self.PTR_REGEX)
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100793 regex = re.compile(regex, flags=re.DOTALL)
Victor Stinner34be8072016-03-14 12:04:26 +0100794 self.assertRegex(out, regex)
795
796 def test_api_misuse(self):
797 out = self.check('import _testcapi; _testcapi.pymem_api_misuse()')
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100798 regex = (r"Debug memory block at address p={ptr}: API 'm'\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100799 r" 16 bytes originally requested\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100800 r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n"
801 r" The [0-9] pad bytes at tail={ptr} are FORBIDDENBYTE, as expected.\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100802 r" The block was made by call #[0-9]+ to debug malloc/realloc.\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100803 r" Data at p: cb cb cb .*\n"
Victor Stinner6453e9e2016-03-15 23:36:28 +0100804 r"\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100805 r"Fatal Python error: bad ID: Allocated using API 'm', verified using API 'r'\n")
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100806 regex = regex.format(ptr=self.PTR_REGEX)
Victor Stinner34be8072016-03-14 12:04:26 +0100807 self.assertRegex(out, regex)
808
Victor Stinnerad524372016-03-16 12:12:53 +0100809 def check_malloc_without_gil(self, code):
Victor Stinnerc4aec362016-03-14 22:26:53 +0100810 out = self.check(code)
811 expected = ('Fatal Python error: Python memory allocator called '
812 'without holding the GIL')
813 self.assertIn(expected, out)
Victor Stinner34be8072016-03-14 12:04:26 +0100814
Victor Stinnerad524372016-03-16 12:12:53 +0100815 def test_pymem_malloc_without_gil(self):
816 # Debug hooks must raise an error if PyMem_Malloc() is called
817 # without holding the GIL
818 code = 'import _testcapi; _testcapi.pymem_malloc_without_gil()'
819 self.check_malloc_without_gil(code)
820
821 def test_pyobject_malloc_without_gil(self):
822 # Debug hooks must raise an error if PyObject_Malloc() is called
823 # without holding the GIL
824 code = 'import _testcapi; _testcapi.pyobject_malloc_without_gil()'
825 self.check_malloc_without_gil(code)
826
Victor Stinnerc4aec362016-03-14 22:26:53 +0100827
828class PyMemMallocDebugTests(PyMemDebugTests):
829 PYTHONMALLOC = 'malloc_debug'
Victor Stinner34be8072016-03-14 12:04:26 +0100830
831
832@unittest.skipUnless(sysconfig.get_config_var('WITH_PYMALLOC') == 1,
833 'need pymalloc')
Victor Stinnerc4aec362016-03-14 22:26:53 +0100834class PyMemPymallocDebugTests(PyMemDebugTests):
835 PYTHONMALLOC = 'pymalloc_debug'
Victor Stinner34be8072016-03-14 12:04:26 +0100836
837
838@unittest.skipUnless(Py_DEBUG, 'need Py_DEBUG')
Victor Stinnerc4aec362016-03-14 22:26:53 +0100839class PyMemDefaultTests(PyMemDebugTests):
840 # test default allocator of Python compiled in debug mode
841 PYTHONMALLOC = ''
Victor Stinner34be8072016-03-14 12:04:26 +0100842
843
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000844if __name__ == "__main__":
Zachary Warec12f09e2013-11-11 22:47:04 -0600845 unittest.main()