blob: 5761686b36a78fba68ec2aaacdf064525c5ced7b [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
Larry Hastings8f904da2012-06-22 03:56:29 -0700444class SkipitemTest(unittest.TestCase):
445
446 def test_skipitem(self):
447 """
448 If this test failed, you probably added a new "format unit"
449 in Python/getargs.c, but neglected to update our poor friend
450 skipitem() in the same file. (If so, shame on you!)
451
Larry Hastings48ed3602012-06-22 12:58:36 -0700452 With a few exceptions**, this function brute-force tests all
453 printable ASCII*** characters (32 to 126 inclusive) as format units,
454 checking to see that PyArg_ParseTupleAndKeywords() return consistent
455 errors both when the unit is attempted to be used and when it is
456 skipped. If the format unit doesn't exist, we'll get one of two
457 specific error messages (one for used, one for skipped); if it does
458 exist we *won't* get that error--we'll get either no error or some
459 other error. If we get the specific "does not exist" error for one
460 test and not for the other, there's a mismatch, and the test fails.
Larry Hastings8f904da2012-06-22 03:56:29 -0700461
Larry Hastings48ed3602012-06-22 12:58:36 -0700462 ** Some format units have special funny semantics and it would
463 be difficult to accomodate them here. Since these are all
464 well-established and properly skipped in skipitem() we can
465 get away with not testing them--this test is really intended
466 to catch *new* format units.
467
468 *** Python C source files must be ASCII. Therefore it's impossible
469 to have non-ASCII format units.
470
Larry Hastings8f904da2012-06-22 03:56:29 -0700471 """
472 empty_tuple = ()
473 tuple_1 = (0,)
474 dict_b = {'b':1}
475 keywords = ["a", "b"]
476
Larry Hastings48ed3602012-06-22 12:58:36 -0700477 for i in range(32, 127):
Larry Hastings8f904da2012-06-22 03:56:29 -0700478 c = chr(i)
479
Larry Hastings8f904da2012-06-22 03:56:29 -0700480 # skip parentheses, the error reporting is inconsistent about them
481 # skip 'e', it's always a two-character code
482 # skip '|' and '$', they don't represent arguments anyway
Larry Hastings48ed3602012-06-22 12:58:36 -0700483 if c in '()e|$':
Larry Hastings8f904da2012-06-22 03:56:29 -0700484 continue
485
486 # test the format unit when not skipped
487 format = c + "i"
488 try:
489 # (note: the format string must be bytes!)
490 _testcapi.parse_tuple_and_keywords(tuple_1, dict_b,
491 format.encode("ascii"), keywords)
492 when_not_skipped = False
Serhiy Storchaka4cd63ef2016-02-08 01:22:47 +0200493 except SystemError as e:
Serhiy Storchakac4b813d2016-02-08 01:06:11 +0200494 s = "argument 1 (impossible<bad format char>)"
Larry Hastings8f904da2012-06-22 03:56:29 -0700495 when_not_skipped = (str(e) == s)
Serhiy Storchakaa9725f82016-02-11 12:41:40 +0200496 except TypeError:
Larry Hastings8f904da2012-06-22 03:56:29 -0700497 when_not_skipped = False
498
499 # test the format unit when skipped
500 optional_format = "|" + format
501 try:
502 _testcapi.parse_tuple_and_keywords(empty_tuple, dict_b,
503 optional_format.encode("ascii"), keywords)
504 when_skipped = False
Serhiy Storchakaa9725f82016-02-11 12:41:40 +0200505 except SystemError as e:
Larry Hastings8f904da2012-06-22 03:56:29 -0700506 s = "impossible<bad format char>: '{}'".format(format)
507 when_skipped = (str(e) == s)
508
509 message = ("test_skipitem_parity: "
510 "detected mismatch between convertsimple and skipitem "
511 "for format unit '{}' ({}), not skipped {}, skipped {}".format(
512 c, i, when_skipped, when_not_skipped))
513 self.assertIs(when_skipped, when_not_skipped, message)
Antoine Pitrou8e605772011-04-25 21:21:07 +0200514
Jesus Cea6e1d2b62012-10-04 16:06:30 +0200515 def test_parse_tuple_and_keywords(self):
516 # parse_tuple_and_keywords error handling tests
517 self.assertRaises(TypeError, _testcapi.parse_tuple_and_keywords,
518 (), {}, 42, [])
519 self.assertRaises(ValueError, _testcapi.parse_tuple_and_keywords,
520 (), {}, b'', 42)
521 self.assertRaises(ValueError, _testcapi.parse_tuple_and_keywords,
522 (), {}, b'', [''] * 42)
523 self.assertRaises(ValueError, _testcapi.parse_tuple_and_keywords,
524 (), {}, b'', [42])
525
Victor Stinner34be8072016-03-14 12:04:26 +0100526
Ezio Melotti29267c82013-02-23 05:52:46 +0200527@unittest.skipUnless(threading, 'Threading required for this test.')
528class TestThreadState(unittest.TestCase):
529
530 @support.reap_threads
531 def test_thread_state(self):
532 # some extra thread-state tests driven via _testcapi
533 def target():
534 idents = []
535
536 def callback():
Ezio Melotti35246bd2013-02-23 05:58:38 +0200537 idents.append(threading.get_ident())
Ezio Melotti29267c82013-02-23 05:52:46 +0200538
539 _testcapi._test_thread_state(callback)
540 a = b = callback
541 time.sleep(1)
542 # Check our main thread is in the list exactly 3 times.
Ezio Melotti35246bd2013-02-23 05:58:38 +0200543 self.assertEqual(idents.count(threading.get_ident()), 3,
Ezio Melotti29267c82013-02-23 05:52:46 +0200544 "Couldn't find main thread correctly in the list")
545
546 target()
547 t = threading.Thread(target=target)
548 t.start()
549 t.join()
550
Victor Stinner34be8072016-03-14 12:04:26 +0100551
Zachary Warec12f09e2013-11-11 22:47:04 -0600552class Test_testcapi(unittest.TestCase):
553 def test__testcapi(self):
554 for name in dir(_testcapi):
555 if name.startswith('test_'):
Zachary Waredfcd6942013-11-11 22:59:23 -0600556 with self.subTest("internal", name=name):
557 test = getattr(_testcapi, name)
558 test()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000559
Victor Stinner34be8072016-03-14 12:04:26 +0100560
561class MallocTests(unittest.TestCase):
562 ENV = 'debug'
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100563 # '0x04c06e0' or '04C06E0'
564 PTR_REGEX = r'(?:0x[0-9a-f]+|[0-9A-F]+)'
Victor Stinner34be8072016-03-14 12:04:26 +0100565
566 def check(self, code):
567 with support.SuppressCrashReport():
568 out = assert_python_failure('-c', code, PYTHONMALLOC=self.ENV)
569 stderr = out.err
570 return stderr.decode('ascii', 'replace')
571
572 def test_buffer_overflow(self):
573 out = self.check('import _testcapi; _testcapi.pymem_buffer_overflow()')
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100574 regex = (r"Debug memory block at address p={ptr}: API 'm'\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100575 r" 16 bytes originally requested\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100576 r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n"
577 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 +0100578 r" at tail\+0: 0x78 \*\*\* OUCH\n"
579 r" at tail\+1: 0xfb\n"
580 r" at tail\+2: 0xfb\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100581 r" .*\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100582 r" The block was made by call #[0-9]+ to debug malloc/realloc.\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100583 r" Data at p: cb cb cb .*\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100584 r"Fatal Python error: bad trailing pad byte")
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100585 regex = regex.format(ptr=self.PTR_REGEX)
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100586 regex = re.compile(regex, flags=re.DOTALL)
Victor Stinner34be8072016-03-14 12:04:26 +0100587 self.assertRegex(out, regex)
588
589 def test_api_misuse(self):
590 out = self.check('import _testcapi; _testcapi.pymem_api_misuse()')
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100591 regex = (r"Debug memory block at address p={ptr}: API 'm'\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100592 r" 16 bytes originally requested\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100593 r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n"
594 r" The [0-9] pad bytes at tail={ptr} are FORBIDDENBYTE, as expected.\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100595 r" The block was made by call #[0-9]+ to debug malloc/realloc.\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100596 r" Data at p: cb cb cb .*\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100597 r"Fatal Python error: bad ID: Allocated using API 'm', verified using API 'r'\n")
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100598 regex = regex.format(ptr=self.PTR_REGEX)
Victor Stinner34be8072016-03-14 12:04:26 +0100599 self.assertRegex(out, regex)
600
601
602class MallocDebugTests(MallocTests):
603 ENV = 'malloc_debug'
604
605
606@unittest.skipUnless(sysconfig.get_config_var('WITH_PYMALLOC') == 1,
607 'need pymalloc')
608class PymallocDebugTests(MallocTests):
609 ENV = 'pymalloc_debug'
610
611
612@unittest.skipUnless(Py_DEBUG, 'need Py_DEBUG')
613class DefaultMallocDebugTests(MallocTests):
614 ENV = ''
615
616
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000617if __name__ == "__main__":
Zachary Warec12f09e2013-11-11 22:47:04 -0600618 unittest.main()