blob: 8f4836a7cec3b250a51fc192354bcbb169a19de8 [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
Antoine Pitrou8e605772011-04-25 21:21:07 +02004import os
Antoine Pitrou2f828f22012-01-18 00:21:11 +01005import pickle
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +00006import random
Victor Stinnerb3adb1a2016-03-14 17:40:09 +01007import re
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +00008import subprocess
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00009import sys
Victor Stinner34be8072016-03-14 12:04:26 +010010import sysconfig
Victor Stinnerefde1462015-03-21 15:04:43 +010011import textwrap
Benjamin Petersona54c9092009-01-13 02:11:23 +000012import time
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000013import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +000014from test import support
Larry Hastingsfcafe432013-11-23 17:35:48 -080015from test.support import MISSING_C_DOCSTRINGS
Berker Peksagce643912015-05-06 06:33:17 +030016from test.support.script_helper import assert_python_failure
Victor Stinner45df8202010-04-28 22:31:17 +000017try:
Stefan Krahfd24f9e2012-08-20 11:04:24 +020018 import _posixsubprocess
19except ImportError:
20 _posixsubprocess = None
21try:
Victor Stinner45df8202010-04-28 22:31:17 +000022 import threading
23except ImportError:
24 threading = None
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
Stefan Krah0ca46242010-06-09 08:56:28 +000053 @unittest.skipUnless(threading, 'Threading required for this test.')
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,
101 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,
109 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,
119 Z(),[b'1'],3,[1, 2],5,6,7,8,9,10,11,12,13,14,15,16,17)
120
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'
225 br'During handling of the above exception, '
226 br'another exception occurred:\n'
227 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
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800241
Victor Stinner45df8202010-04-28 22:31:17 +0000242@unittest.skipUnless(threading, 'Threading required for this test.')
Benjamin Petersona54c9092009-01-13 02:11:23 +0000243class TestPendingCalls(unittest.TestCase):
244
245 def pendingcalls_submit(self, l, n):
246 def callback():
247 #this function can be interrupted by thread switching so let's
248 #use an atomic operation
249 l.append(None)
250
251 for i in range(n):
252 time.sleep(random.random()*0.02) #0.01 secs on average
253 #try submitting callback until successful.
254 #rely on regular interrupt to flush queue if we are
255 #unsuccessful.
256 while True:
257 if _testcapi._pending_threadfunc(callback):
258 break;
259
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000260 def pendingcalls_wait(self, l, n, context = None):
Benjamin Petersona54c9092009-01-13 02:11:23 +0000261 #now, stick around until l[0] has grown to 10
262 count = 0;
263 while len(l) != n:
264 #this busy loop is where we expect to be interrupted to
265 #run our callbacks. Note that callbacks are only run on the
266 #main thread
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000267 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +0000268 print("(%i)"%(len(l),),)
269 for i in range(1000):
270 a = i*i
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000271 if context and not context.event.is_set():
272 continue
Benjamin Petersona54c9092009-01-13 02:11:23 +0000273 count += 1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000274 self.assertTrue(count < 10000,
Benjamin Petersona54c9092009-01-13 02:11:23 +0000275 "timeout waiting for %i callbacks, got %i"%(n, len(l)))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000276 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +0000277 print("(%i)"%(len(l),))
278
279 def test_pendingcalls_threaded(self):
Benjamin Petersona54c9092009-01-13 02:11:23 +0000280
281 #do every callback on a separate thread
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000282 n = 32 #total callbacks
Benjamin Petersona54c9092009-01-13 02:11:23 +0000283 threads = []
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000284 class foo(object):pass
285 context = foo()
286 context.l = []
287 context.n = 2 #submits per thread
288 context.nThreads = n // context.n
289 context.nFinished = 0
290 context.lock = threading.Lock()
291 context.event = threading.Event()
292
Serhiy Storchaka263dcd22015-04-01 13:01:14 +0300293 threads = [threading.Thread(target=self.pendingcalls_thread,
294 args=(context,))
295 for i in range(context.nThreads)]
296 with support.start_threads(threads):
297 self.pendingcalls_wait(context.l, n, context)
Benjamin Petersona54c9092009-01-13 02:11:23 +0000298
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000299 def pendingcalls_thread(self, context):
300 try:
301 self.pendingcalls_submit(context.l, context.n)
302 finally:
303 with context.lock:
304 context.nFinished += 1
305 nFinished = context.nFinished
306 if False and support.verbose:
307 print("finished threads: ", nFinished)
308 if nFinished == context.nThreads:
309 context.event.set()
310
Benjamin Petersona54c9092009-01-13 02:11:23 +0000311 def test_pendingcalls_non_threaded(self):
Ezio Melotti13925002011-03-16 11:05:33 +0200312 #again, just using the main thread, likely they will all be dispatched at
Benjamin Petersona54c9092009-01-13 02:11:23 +0000313 #once. It is ok to ask for too many, because we loop until we find a slot.
314 #the loop can be interrupted to dispatch.
315 #there are only 32 dispatch slots, so we go for twice that!
316 l = []
317 n = 64
318 self.pendingcalls_submit(l, n)
319 self.pendingcalls_wait(l, n)
320
Antoine Pitrou7a2572c2013-08-01 20:43:26 +0200321
322class SubinterpreterTest(unittest.TestCase):
323
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100324 def test_subinterps(self):
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100325 import builtins
326 r, w = os.pipe()
327 code = """if 1:
328 import sys, builtins, pickle
329 with open({:d}, "wb") as f:
330 pickle.dump(id(sys.modules), f)
331 pickle.dump(id(builtins), f)
332 """.format(w)
333 with open(r, "rb") as f:
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100334 ret = support.run_in_subinterp(code)
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100335 self.assertEqual(ret, 0)
336 self.assertNotEqual(pickle.load(f), id(sys.modules))
337 self.assertNotEqual(pickle.load(f), id(builtins))
338
Antoine Pitrou7a2572c2013-08-01 20:43:26 +0200339
Martin v. Löwisc15bdef2009-05-29 14:47:46 +0000340# Bug #6012
341class Test6012(unittest.TestCase):
342 def test(self):
343 self.assertEqual(_testcapi.argparsing("Hello", "World"), 1)
Benjamin Petersona54c9092009-01-13 02:11:23 +0000344
Antoine Pitrou8e605772011-04-25 21:21:07 +0200345
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000346class EmbeddingTests(unittest.TestCase):
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000347 def setUp(self):
Zachary Ware6d8a2602015-12-05 00:16:55 -0600348 here = os.path.abspath(__file__)
349 basepath = os.path.dirname(os.path.dirname(os.path.dirname(here)))
Nick Coghlan4e641df2013-11-03 16:54:46 +1000350 exename = "_testembed"
351 if sys.platform.startswith("win"):
352 ext = ("_d" if "_d" in sys.executable else "") + ".exe"
353 exename += ext
354 exepath = os.path.dirname(sys.executable)
355 else:
Nick Coghlanbca9acf2014-09-25 19:48:15 +1000356 exepath = os.path.join(basepath, "Programs")
Nick Coghlan4e641df2013-11-03 16:54:46 +1000357 self.test_exe = exe = os.path.join(exepath, exename)
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000358 if not os.path.exists(exe):
359 self.skipTest("%r doesn't exist" % exe)
Antoine Pitrou8e605772011-04-25 21:21:07 +0200360 # This is needed otherwise we get a fatal error:
361 # "Py_Initialize: Unable to get the locale encoding
362 # LookupError: no codec search functions registered: can't find encoding"
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000363 self.oldcwd = os.getcwd()
Antoine Pitrou8e605772011-04-25 21:21:07 +0200364 os.chdir(basepath)
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000365
366 def tearDown(self):
367 os.chdir(self.oldcwd)
368
369 def run_embedded_interpreter(self, *args):
370 """Runs a test in the embedded interpreter"""
371 cmd = [self.test_exe]
372 cmd.extend(args)
373 p = subprocess.Popen(cmd,
374 stdout=subprocess.PIPE,
Steve Dower86e9deb2014-11-01 15:11:05 -0700375 stderr=subprocess.PIPE,
376 universal_newlines=True)
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000377 (out, err) = p.communicate()
378 self.assertEqual(p.returncode, 0,
379 "bad returncode %d, stderr is %r" %
380 (p.returncode, err))
Steve Dower86e9deb2014-11-01 15:11:05 -0700381 return out, err
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000382
383 def test_subinterps(self):
384 # This is just a "don't crash" test
385 out, err = self.run_embedded_interpreter()
386 if support.verbose:
387 print()
388 print(out)
389 print(err)
390
Nick Coghlan4e641df2013-11-03 16:54:46 +1000391 @staticmethod
392 def _get_default_pipe_encoding():
393 rp, wp = os.pipe()
394 try:
395 with os.fdopen(wp, 'w') as w:
396 default_pipe_encoding = w.encoding
397 finally:
398 os.close(rp)
399 return default_pipe_encoding
400
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000401 def test_forced_io_encoding(self):
402 # Checks forced configuration of embedded interpreter IO streams
403 out, err = self.run_embedded_interpreter("forced_io_encoding")
404 if support.verbose:
405 print()
406 print(out)
407 print(err)
Victor Stinnerb2bef622014-03-18 02:38:12 +0100408 expected_errors = sys.__stdout__.errors
Nick Coghlan4e641df2013-11-03 16:54:46 +1000409 expected_stdin_encoding = sys.__stdin__.encoding
410 expected_pipe_encoding = self._get_default_pipe_encoding()
Steve Dower86e9deb2014-11-01 15:11:05 -0700411 expected_output = '\n'.join([
Nick Coghlan4e641df2013-11-03 16:54:46 +1000412 "--- Use defaults ---",
413 "Expected encoding: default",
414 "Expected errors: default",
Victor Stinnerb2bef622014-03-18 02:38:12 +0100415 "stdin: {in_encoding}:{errors}",
416 "stdout: {out_encoding}:{errors}",
417 "stderr: {out_encoding}:backslashreplace",
Nick Coghlan4e641df2013-11-03 16:54:46 +1000418 "--- Set errors only ---",
419 "Expected encoding: default",
Victor Stinnerb2bef622014-03-18 02:38:12 +0100420 "Expected errors: ignore",
421 "stdin: {in_encoding}:ignore",
422 "stdout: {out_encoding}:ignore",
423 "stderr: {out_encoding}:backslashreplace",
Nick Coghlan4e641df2013-11-03 16:54:46 +1000424 "--- Set encoding only ---",
425 "Expected encoding: latin-1",
426 "Expected errors: default",
Victor Stinnerb2bef622014-03-18 02:38:12 +0100427 "stdin: latin-1:{errors}",
428 "stdout: latin-1:{errors}",
Nick Coghlan4e641df2013-11-03 16:54:46 +1000429 "stderr: latin-1:backslashreplace",
430 "--- Set encoding and errors ---",
431 "Expected encoding: latin-1",
Victor Stinnerb2bef622014-03-18 02:38:12 +0100432 "Expected errors: replace",
433 "stdin: latin-1:replace",
434 "stdout: latin-1:replace",
435 "stderr: latin-1:backslashreplace"])
436 expected_output = expected_output.format(
437 in_encoding=expected_stdin_encoding,
438 out_encoding=expected_pipe_encoding,
439 errors=expected_errors)
Nick Coghlan3321fb82013-10-18 23:59:58 +1000440 # This is useful if we ever trip over odd platform behaviour
Nick Coghlan6508dc52013-10-18 01:44:22 +1000441 self.maxDiff = None
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000442 self.assertEqual(out.strip(), expected_output)
Antoine Pitrou8e605772011-04-25 21:21:07 +0200443
Victor Stinnerc4aec362016-03-14 22:26:53 +0100444
Larry Hastings8f904da2012-06-22 03:56:29 -0700445class SkipitemTest(unittest.TestCase):
446
447 def test_skipitem(self):
448 """
449 If this test failed, you probably added a new "format unit"
450 in Python/getargs.c, but neglected to update our poor friend
451 skipitem() in the same file. (If so, shame on you!)
452
Larry Hastings48ed3602012-06-22 12:58:36 -0700453 With a few exceptions**, this function brute-force tests all
454 printable ASCII*** characters (32 to 126 inclusive) as format units,
455 checking to see that PyArg_ParseTupleAndKeywords() return consistent
456 errors both when the unit is attempted to be used and when it is
457 skipped. If the format unit doesn't exist, we'll get one of two
458 specific error messages (one for used, one for skipped); if it does
459 exist we *won't* get that error--we'll get either no error or some
460 other error. If we get the specific "does not exist" error for one
461 test and not for the other, there's a mismatch, and the test fails.
Larry Hastings8f904da2012-06-22 03:56:29 -0700462
Larry Hastings48ed3602012-06-22 12:58:36 -0700463 ** Some format units have special funny semantics and it would
464 be difficult to accomodate them here. Since these are all
465 well-established and properly skipped in skipitem() we can
466 get away with not testing them--this test is really intended
467 to catch *new* format units.
468
469 *** Python C source files must be ASCII. Therefore it's impossible
470 to have non-ASCII format units.
471
Larry Hastings8f904da2012-06-22 03:56:29 -0700472 """
473 empty_tuple = ()
474 tuple_1 = (0,)
475 dict_b = {'b':1}
476 keywords = ["a", "b"]
477
Larry Hastings48ed3602012-06-22 12:58:36 -0700478 for i in range(32, 127):
Larry Hastings8f904da2012-06-22 03:56:29 -0700479 c = chr(i)
480
Larry Hastings8f904da2012-06-22 03:56:29 -0700481 # skip parentheses, the error reporting is inconsistent about them
482 # skip 'e', it's always a two-character code
483 # skip '|' and '$', they don't represent arguments anyway
Larry Hastings48ed3602012-06-22 12:58:36 -0700484 if c in '()e|$':
Larry Hastings8f904da2012-06-22 03:56:29 -0700485 continue
486
487 # test the format unit when not skipped
488 format = c + "i"
489 try:
490 # (note: the format string must be bytes!)
491 _testcapi.parse_tuple_and_keywords(tuple_1, dict_b,
492 format.encode("ascii"), keywords)
493 when_not_skipped = False
Serhiy Storchaka4cd63ef2016-02-08 01:22:47 +0200494 except SystemError as e:
Serhiy Storchakac4b813d2016-02-08 01:06:11 +0200495 s = "argument 1 (impossible<bad format char>)"
Larry Hastings8f904da2012-06-22 03:56:29 -0700496 when_not_skipped = (str(e) == s)
Serhiy Storchakaa9725f82016-02-11 12:41:40 +0200497 except TypeError:
Larry Hastings8f904da2012-06-22 03:56:29 -0700498 when_not_skipped = False
499
500 # test the format unit when skipped
501 optional_format = "|" + format
502 try:
503 _testcapi.parse_tuple_and_keywords(empty_tuple, dict_b,
504 optional_format.encode("ascii"), keywords)
505 when_skipped = False
Serhiy Storchakaa9725f82016-02-11 12:41:40 +0200506 except SystemError as e:
Larry Hastings8f904da2012-06-22 03:56:29 -0700507 s = "impossible<bad format char>: '{}'".format(format)
508 when_skipped = (str(e) == s)
509
510 message = ("test_skipitem_parity: "
511 "detected mismatch between convertsimple and skipitem "
512 "for format unit '{}' ({}), not skipped {}, skipped {}".format(
513 c, i, when_skipped, when_not_skipped))
514 self.assertIs(when_skipped, when_not_skipped, message)
Antoine Pitrou8e605772011-04-25 21:21:07 +0200515
Jesus Cea6e1d2b62012-10-04 16:06:30 +0200516 def test_parse_tuple_and_keywords(self):
517 # parse_tuple_and_keywords error handling tests
518 self.assertRaises(TypeError, _testcapi.parse_tuple_and_keywords,
519 (), {}, 42, [])
520 self.assertRaises(ValueError, _testcapi.parse_tuple_and_keywords,
521 (), {}, b'', 42)
522 self.assertRaises(ValueError, _testcapi.parse_tuple_and_keywords,
523 (), {}, b'', [''] * 42)
524 self.assertRaises(ValueError, _testcapi.parse_tuple_and_keywords,
525 (), {}, b'', [42])
526
Victor Stinner34be8072016-03-14 12:04:26 +0100527
Ezio Melotti29267c82013-02-23 05:52:46 +0200528@unittest.skipUnless(threading, 'Threading required for this test.')
529class TestThreadState(unittest.TestCase):
530
531 @support.reap_threads
532 def test_thread_state(self):
533 # some extra thread-state tests driven via _testcapi
534 def target():
535 idents = []
536
537 def callback():
Ezio Melotti35246bd2013-02-23 05:58:38 +0200538 idents.append(threading.get_ident())
Ezio Melotti29267c82013-02-23 05:52:46 +0200539
540 _testcapi._test_thread_state(callback)
541 a = b = callback
542 time.sleep(1)
543 # Check our main thread is in the list exactly 3 times.
Ezio Melotti35246bd2013-02-23 05:58:38 +0200544 self.assertEqual(idents.count(threading.get_ident()), 3,
Ezio Melotti29267c82013-02-23 05:52:46 +0200545 "Couldn't find main thread correctly in the list")
546
547 target()
548 t = threading.Thread(target=target)
549 t.start()
550 t.join()
551
Victor Stinner34be8072016-03-14 12:04:26 +0100552
Zachary Warec12f09e2013-11-11 22:47:04 -0600553class Test_testcapi(unittest.TestCase):
554 def test__testcapi(self):
555 for name in dir(_testcapi):
556 if name.startswith('test_'):
Zachary Waredfcd6942013-11-11 22:59:23 -0600557 with self.subTest("internal", name=name):
558 test = getattr(_testcapi, name)
559 test()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000560
Victor Stinner34be8072016-03-14 12:04:26 +0100561
Victor Stinnerc4aec362016-03-14 22:26:53 +0100562class PyMemDebugTests(unittest.TestCase):
563 PYTHONMALLOC = 'debug'
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100564 # '0x04c06e0' or '04C06E0'
Victor Stinner08572f62016-03-14 21:55:43 +0100565 PTR_REGEX = r'(?:0x)?[0-9a-fA-F]+'
Victor Stinner34be8072016-03-14 12:04:26 +0100566
567 def check(self, code):
568 with support.SuppressCrashReport():
Victor Stinnerc4aec362016-03-14 22:26:53 +0100569 out = assert_python_failure('-c', code,
570 PYTHONMALLOC=self.PYTHONMALLOC)
Victor Stinner34be8072016-03-14 12:04:26 +0100571 stderr = out.err
572 return stderr.decode('ascii', 'replace')
573
574 def test_buffer_overflow(self):
575 out = self.check('import _testcapi; _testcapi.pymem_buffer_overflow()')
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100576 regex = (r"Debug memory block at address p={ptr}: API 'm'\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100577 r" 16 bytes originally requested\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100578 r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n"
579 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 +0100580 r" at tail\+0: 0x78 \*\*\* OUCH\n"
581 r" at tail\+1: 0xfb\n"
582 r" at tail\+2: 0xfb\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100583 r" .*\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100584 r" The block was made by call #[0-9]+ to debug malloc/realloc.\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100585 r" Data at p: cb cb cb .*\n"
Victor Stinner6453e9e2016-03-15 23:36:28 +0100586 r"\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100587 r"Fatal Python error: bad trailing pad byte")
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100588 regex = regex.format(ptr=self.PTR_REGEX)
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100589 regex = re.compile(regex, flags=re.DOTALL)
Victor Stinner34be8072016-03-14 12:04:26 +0100590 self.assertRegex(out, regex)
591
592 def test_api_misuse(self):
593 out = self.check('import _testcapi; _testcapi.pymem_api_misuse()')
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100594 regex = (r"Debug memory block at address p={ptr}: API 'm'\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100595 r" 16 bytes originally requested\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100596 r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n"
597 r" The [0-9] pad bytes at tail={ptr} are FORBIDDENBYTE, as expected.\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100598 r" The block was made by call #[0-9]+ to debug malloc/realloc.\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100599 r" Data at p: cb cb cb .*\n"
Victor Stinner6453e9e2016-03-15 23:36:28 +0100600 r"\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100601 r"Fatal Python error: bad ID: Allocated using API 'm', verified using API 'r'\n")
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100602 regex = regex.format(ptr=self.PTR_REGEX)
Victor Stinner34be8072016-03-14 12:04:26 +0100603 self.assertRegex(out, regex)
604
Victor Stinnerad524372016-03-16 12:12:53 +0100605 def check_malloc_without_gil(self, code):
Victor Stinnerc4aec362016-03-14 22:26:53 +0100606 out = self.check(code)
607 expected = ('Fatal Python error: Python memory allocator called '
608 'without holding the GIL')
609 self.assertIn(expected, out)
Victor Stinner34be8072016-03-14 12:04:26 +0100610
Victor Stinnerad524372016-03-16 12:12:53 +0100611 def test_pymem_malloc_without_gil(self):
612 # Debug hooks must raise an error if PyMem_Malloc() is called
613 # without holding the GIL
614 code = 'import _testcapi; _testcapi.pymem_malloc_without_gil()'
615 self.check_malloc_without_gil(code)
616
617 def test_pyobject_malloc_without_gil(self):
618 # Debug hooks must raise an error if PyObject_Malloc() is called
619 # without holding the GIL
620 code = 'import _testcapi; _testcapi.pyobject_malloc_without_gil()'
621 self.check_malloc_without_gil(code)
622
Victor Stinnerc4aec362016-03-14 22:26:53 +0100623
624class PyMemMallocDebugTests(PyMemDebugTests):
625 PYTHONMALLOC = 'malloc_debug'
Victor Stinner34be8072016-03-14 12:04:26 +0100626
627
628@unittest.skipUnless(sysconfig.get_config_var('WITH_PYMALLOC') == 1,
629 'need pymalloc')
Victor Stinnerc4aec362016-03-14 22:26:53 +0100630class PyMemPymallocDebugTests(PyMemDebugTests):
631 PYTHONMALLOC = 'pymalloc_debug'
Victor Stinner34be8072016-03-14 12:04:26 +0100632
633
634@unittest.skipUnless(Py_DEBUG, 'need Py_DEBUG')
Victor Stinnerc4aec362016-03-14 22:26:53 +0100635class PyMemDefaultTests(PyMemDebugTests):
636 # test default allocator of Python compiled in debug mode
637 PYTHONMALLOC = ''
Victor Stinner34be8072016-03-14 12:04:26 +0100638
639
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000640if __name__ == "__main__":
Zachary Warec12f09e2013-11-11 22:47:04 -0600641 unittest.main()