blob: 74ec6c51558f137a7466233ecfbc3187cb179a1c [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
7import subprocess
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00008import sys
Victor Stinnerefde1462015-03-21 15:04:43 +01009import textwrap
Benjamin Petersona54c9092009-01-13 02:11:23 +000010import time
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000011import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +000012from test import support
Larry Hastingsfcafe432013-11-23 17:35:48 -080013from test.support import MISSING_C_DOCSTRINGS
Berker Peksagce643912015-05-06 06:33:17 +030014from test.support.script_helper import assert_python_failure
Victor Stinner45df8202010-04-28 22:31:17 +000015try:
Stefan Krahfd24f9e2012-08-20 11:04:24 +020016 import _posixsubprocess
17except ImportError:
18 _posixsubprocess = None
19try:
Victor Stinner45df8202010-04-28 22:31:17 +000020 import threading
21except ImportError:
22 threading = None
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +020023# Skip this test if the _testcapi module isn't available.
24_testcapi = support.import_module('_testcapi')
Tim Peters9ea17ac2001-02-02 05:57:15 +000025
Victor Stinnerefde1462015-03-21 15:04:43 +010026# Were we compiled --with-pydebug or with #define Py_DEBUG?
27Py_DEBUG = hasattr(sys, 'gettotalrefcount')
28
Benjamin Petersona54c9092009-01-13 02:11:23 +000029
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000030def testfunction(self):
31 """some doc"""
32 return self
33
34class InstanceMethod:
35 id = _testcapi.instancemethod(id)
36 testfunction = _testcapi.instancemethod(testfunction)
37
38class CAPITest(unittest.TestCase):
39
40 def test_instancemethod(self):
41 inst = InstanceMethod()
42 self.assertEqual(id(inst), inst.id())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000043 self.assertTrue(inst.testfunction() is inst)
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000044 self.assertEqual(inst.testfunction.__doc__, testfunction.__doc__)
45 self.assertEqual(InstanceMethod.testfunction.__doc__, testfunction.__doc__)
46
47 InstanceMethod.testfunction.attribute = "test"
48 self.assertEqual(testfunction.attribute, "test")
49 self.assertRaises(AttributeError, setattr, inst.testfunction, "attribute", "test")
50
Stefan Krah0ca46242010-06-09 08:56:28 +000051 @unittest.skipUnless(threading, 'Threading required for this test.')
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000052 def test_no_FatalError_infinite_loop(self):
Antoine Pitrou77e904e2013-10-08 23:04:32 +020053 with support.SuppressCrashReport():
Ezio Melotti25a40452013-03-05 20:26:17 +020054 p = subprocess.Popen([sys.executable, "-c",
Ezio Melottie1857d92013-03-05 20:31:34 +020055 'import _testcapi;'
56 '_testcapi.crash_no_current_thread()'],
57 stdout=subprocess.PIPE,
58 stderr=subprocess.PIPE)
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000059 (out, err) = p.communicate()
60 self.assertEqual(out, b'')
61 # This used to cause an infinite loop.
Vinay Sajip73954042012-05-06 11:34:50 +010062 self.assertTrue(err.rstrip().startswith(
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000063 b'Fatal Python error:'
Vinay Sajip73954042012-05-06 11:34:50 +010064 b' PyThreadState_Get: no current thread'))
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000065
Antoine Pitrou915605c2011-02-24 20:53:48 +000066 def test_memoryview_from_NULL_pointer(self):
67 self.assertRaises(ValueError, _testcapi.make_memoryview_from_NULL_pointer)
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000068
Martin v. Löwisaa2efcb2012-04-19 14:33:43 +020069 def test_exc_info(self):
70 raised_exception = ValueError("5")
71 new_exc = TypeError("TEST")
72 try:
73 raise raised_exception
74 except ValueError as e:
75 tb = e.__traceback__
76 orig_sys_exc_info = sys.exc_info()
77 orig_exc_info = _testcapi.set_exc_info(new_exc.__class__, new_exc, None)
78 new_sys_exc_info = sys.exc_info()
79 new_exc_info = _testcapi.set_exc_info(*orig_exc_info)
80 reset_sys_exc_info = sys.exc_info()
81
82 self.assertEqual(orig_exc_info[1], e)
83
84 self.assertSequenceEqual(orig_exc_info, (raised_exception.__class__, raised_exception, tb))
85 self.assertSequenceEqual(orig_sys_exc_info, orig_exc_info)
86 self.assertSequenceEqual(reset_sys_exc_info, orig_exc_info)
87 self.assertSequenceEqual(new_exc_info, (new_exc.__class__, new_exc, None))
88 self.assertSequenceEqual(new_sys_exc_info, new_exc_info)
89 else:
90 self.assertTrue(False)
91
Stefan Krahfd24f9e2012-08-20 11:04:24 +020092 @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
93 def test_seq_bytes_to_charp_array(self):
94 # Issue #15732: crash in _PySequence_BytesToCharpArray()
95 class Z(object):
96 def __len__(self):
97 return 1
98 self.assertRaises(TypeError, _posixsubprocess.fork_exec,
99 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 +0200100 # Issue #15736: overflow in _PySequence_BytesToCharpArray()
101 class Z(object):
102 def __len__(self):
103 return sys.maxsize
104 def __getitem__(self, i):
105 return b'x'
106 self.assertRaises(MemoryError, _posixsubprocess.fork_exec,
107 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 +0200108
Stefan Krahdb579d72012-08-20 14:36:47 +0200109 @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
110 def test_subprocess_fork_exec(self):
111 class Z(object):
112 def __len__(self):
113 return 1
114
115 # Issue #15738: crash in subprocess_fork_exec()
116 self.assertRaises(TypeError, _posixsubprocess.fork_exec,
117 Z(),[b'1'],3,[1, 2],5,6,7,8,9,10,11,12,13,14,15,16,17)
118
Larry Hastingsfcafe432013-11-23 17:35:48 -0800119 @unittest.skipIf(MISSING_C_DOCSTRINGS,
120 "Signature information for builtins requires docstrings")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800121 def test_docstring_signature_parsing(self):
122
123 self.assertEqual(_testcapi.no_docstring.__doc__, None)
124 self.assertEqual(_testcapi.no_docstring.__text_signature__, None)
125
Zachary Ware8ef887c2015-04-13 18:22:35 -0500126 self.assertEqual(_testcapi.docstring_empty.__doc__, None)
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800127 self.assertEqual(_testcapi.docstring_empty.__text_signature__, None)
128
129 self.assertEqual(_testcapi.docstring_no_signature.__doc__,
130 "This docstring has no signature.")
131 self.assertEqual(_testcapi.docstring_no_signature.__text_signature__, None)
132
133 self.assertEqual(_testcapi.docstring_with_invalid_signature.__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800134 "docstring_with_invalid_signature($module, /, boo)\n"
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800135 "\n"
136 "This docstring has an invalid signature."
137 )
138 self.assertEqual(_testcapi.docstring_with_invalid_signature.__text_signature__, None)
139
Larry Hastings2623c8c2014-02-08 22:15:29 -0800140 self.assertEqual(_testcapi.docstring_with_invalid_signature2.__doc__,
141 "docstring_with_invalid_signature2($module, /, boo)\n"
142 "\n"
143 "--\n"
144 "\n"
145 "This docstring also has an invalid signature."
146 )
147 self.assertEqual(_testcapi.docstring_with_invalid_signature2.__text_signature__, None)
148
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800149 self.assertEqual(_testcapi.docstring_with_signature.__doc__,
150 "This docstring has a valid signature.")
Larry Hastings2623c8c2014-02-08 22:15:29 -0800151 self.assertEqual(_testcapi.docstring_with_signature.__text_signature__, "($module, /, sig)")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800152
Zachary Ware8ef887c2015-04-13 18:22:35 -0500153 self.assertEqual(_testcapi.docstring_with_signature_but_no_doc.__doc__, None)
154 self.assertEqual(_testcapi.docstring_with_signature_but_no_doc.__text_signature__,
155 "($module, /, sig)")
156
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800157 self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800158 "\nThis docstring has a valid signature and some extra newlines.")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800159 self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__text_signature__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800160 "($module, /, parameter)")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800161
Benjamin Petersond51374e2014-04-09 23:55:56 -0400162 def test_c_type_with_matrix_multiplication(self):
163 M = _testcapi.matmulType
164 m1 = M()
165 m2 = M()
166 self.assertEqual(m1 @ m2, ("matmul", m1, m2))
167 self.assertEqual(m1 @ 42, ("matmul", m1, 42))
168 self.assertEqual(42 @ m1, ("matmul", 42, m1))
169 o = m1
170 o @= m2
171 self.assertEqual(o, ("imatmul", m1, m2))
172 o = m1
173 o @= 42
174 self.assertEqual(o, ("imatmul", m1, 42))
175 o = 42
176 o @= m1
177 self.assertEqual(o, ("matmul", 42, m1))
178
Victor Stinnerefde1462015-03-21 15:04:43 +0100179 def test_return_null_without_error(self):
180 # Issue #23571: A function must not return NULL without setting an
181 # error
182 if Py_DEBUG:
183 code = textwrap.dedent("""
184 import _testcapi
185 from test import support
186
187 with support.SuppressCrashReport():
188 _testcapi.return_null_without_error()
189 """)
190 rc, out, err = assert_python_failure('-c', code)
Victor Stinner381a9bc2015-03-24 14:01:32 +0100191 self.assertRegex(err.replace(b'\r', b''),
Victor Stinner944fbcc2015-03-24 16:28:52 +0100192 br'Fatal Python error: a function returned NULL '
193 br'without setting an error\n'
Victor Stinner381a9bc2015-03-24 14:01:32 +0100194 br'SystemError: <built-in function '
195 br'return_null_without_error> returned NULL '
196 br'without setting an error\n'
197 br'\n'
198 br'Current thread.*:\n'
199 br' File .*", line 6 in <module>')
Victor Stinnerefde1462015-03-21 15:04:43 +0100200 else:
201 with self.assertRaises(SystemError) as cm:
202 _testcapi.return_null_without_error()
203 self.assertRegex(str(cm.exception),
204 'return_null_without_error.* '
205 'returned NULL without setting an error')
206
207 def test_return_result_with_error(self):
208 # Issue #23571: A function must not return a result with an error set
209 if Py_DEBUG:
210 code = textwrap.dedent("""
211 import _testcapi
212 from test import support
213
214 with support.SuppressCrashReport():
215 _testcapi.return_result_with_error()
216 """)
217 rc, out, err = assert_python_failure('-c', code)
Victor Stinner381a9bc2015-03-24 14:01:32 +0100218 self.assertRegex(err.replace(b'\r', b''),
Victor Stinner944fbcc2015-03-24 16:28:52 +0100219 br'Fatal Python error: a function returned a '
220 br'result with an error set\n'
Victor Stinner381a9bc2015-03-24 14:01:32 +0100221 br'ValueError\n'
222 br'\n'
223 br'During handling of the above exception, '
224 br'another exception occurred:\n'
225 br'\n'
226 br'SystemError: <built-in '
227 br'function return_result_with_error> '
228 br'returned a result with an error set\n'
229 br'\n'
230 br'Current thread.*:\n'
231 br' File .*, line 6 in <module>')
Victor Stinnerefde1462015-03-21 15:04:43 +0100232 else:
233 with self.assertRaises(SystemError) as cm:
234 _testcapi.return_result_with_error()
235 self.assertRegex(str(cm.exception),
236 'return_result_with_error.* '
237 'returned a result with an error set')
238
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800239
Victor Stinner45df8202010-04-28 22:31:17 +0000240@unittest.skipUnless(threading, 'Threading required for this test.')
Benjamin Petersona54c9092009-01-13 02:11:23 +0000241class TestPendingCalls(unittest.TestCase):
242
243 def pendingcalls_submit(self, l, n):
244 def callback():
245 #this function can be interrupted by thread switching so let's
246 #use an atomic operation
247 l.append(None)
248
249 for i in range(n):
250 time.sleep(random.random()*0.02) #0.01 secs on average
251 #try submitting callback until successful.
252 #rely on regular interrupt to flush queue if we are
253 #unsuccessful.
254 while True:
255 if _testcapi._pending_threadfunc(callback):
256 break;
257
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000258 def pendingcalls_wait(self, l, n, context = None):
Benjamin Petersona54c9092009-01-13 02:11:23 +0000259 #now, stick around until l[0] has grown to 10
260 count = 0;
261 while len(l) != n:
262 #this busy loop is where we expect to be interrupted to
263 #run our callbacks. Note that callbacks are only run on the
264 #main thread
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000265 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +0000266 print("(%i)"%(len(l),),)
267 for i in range(1000):
268 a = i*i
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000269 if context and not context.event.is_set():
270 continue
Benjamin Petersona54c9092009-01-13 02:11:23 +0000271 count += 1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000272 self.assertTrue(count < 10000,
Benjamin Petersona54c9092009-01-13 02:11:23 +0000273 "timeout waiting for %i callbacks, got %i"%(n, len(l)))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000274 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +0000275 print("(%i)"%(len(l),))
276
277 def test_pendingcalls_threaded(self):
Benjamin Petersona54c9092009-01-13 02:11:23 +0000278
279 #do every callback on a separate thread
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000280 n = 32 #total callbacks
Benjamin Petersona54c9092009-01-13 02:11:23 +0000281 threads = []
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000282 class foo(object):pass
283 context = foo()
284 context.l = []
285 context.n = 2 #submits per thread
286 context.nThreads = n // context.n
287 context.nFinished = 0
288 context.lock = threading.Lock()
289 context.event = threading.Event()
290
Serhiy Storchaka263dcd22015-04-01 13:01:14 +0300291 threads = [threading.Thread(target=self.pendingcalls_thread,
292 args=(context,))
293 for i in range(context.nThreads)]
294 with support.start_threads(threads):
295 self.pendingcalls_wait(context.l, n, context)
Benjamin Petersona54c9092009-01-13 02:11:23 +0000296
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000297 def pendingcalls_thread(self, context):
298 try:
299 self.pendingcalls_submit(context.l, context.n)
300 finally:
301 with context.lock:
302 context.nFinished += 1
303 nFinished = context.nFinished
304 if False and support.verbose:
305 print("finished threads: ", nFinished)
306 if nFinished == context.nThreads:
307 context.event.set()
308
Benjamin Petersona54c9092009-01-13 02:11:23 +0000309 def test_pendingcalls_non_threaded(self):
Ezio Melotti13925002011-03-16 11:05:33 +0200310 #again, just using the main thread, likely they will all be dispatched at
Benjamin Petersona54c9092009-01-13 02:11:23 +0000311 #once. It is ok to ask for too many, because we loop until we find a slot.
312 #the loop can be interrupted to dispatch.
313 #there are only 32 dispatch slots, so we go for twice that!
314 l = []
315 n = 64
316 self.pendingcalls_submit(l, n)
317 self.pendingcalls_wait(l, n)
318
Antoine Pitrou7a2572c2013-08-01 20:43:26 +0200319
320class SubinterpreterTest(unittest.TestCase):
321
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100322 def test_subinterps(self):
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100323 import builtins
324 r, w = os.pipe()
325 code = """if 1:
326 import sys, builtins, pickle
327 with open({:d}, "wb") as f:
328 pickle.dump(id(sys.modules), f)
329 pickle.dump(id(builtins), f)
330 """.format(w)
331 with open(r, "rb") as f:
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100332 ret = support.run_in_subinterp(code)
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100333 self.assertEqual(ret, 0)
334 self.assertNotEqual(pickle.load(f), id(sys.modules))
335 self.assertNotEqual(pickle.load(f), id(builtins))
336
Antoine Pitrou7a2572c2013-08-01 20:43:26 +0200337
Martin v. Löwisc15bdef2009-05-29 14:47:46 +0000338# Bug #6012
339class Test6012(unittest.TestCase):
340 def test(self):
341 self.assertEqual(_testcapi.argparsing("Hello", "World"), 1)
Benjamin Petersona54c9092009-01-13 02:11:23 +0000342
Antoine Pitrou8e605772011-04-25 21:21:07 +0200343
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000344class EmbeddingTests(unittest.TestCase):
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000345 def setUp(self):
Zachary Ware6d8a2602015-12-05 00:16:55 -0600346 here = os.path.abspath(__file__)
347 basepath = os.path.dirname(os.path.dirname(os.path.dirname(here)))
Nick Coghlan4e641df2013-11-03 16:54:46 +1000348 exename = "_testembed"
349 if sys.platform.startswith("win"):
350 ext = ("_d" if "_d" in sys.executable else "") + ".exe"
351 exename += ext
352 exepath = os.path.dirname(sys.executable)
353 else:
Nick Coghlanbca9acf2014-09-25 19:48:15 +1000354 exepath = os.path.join(basepath, "Programs")
Nick Coghlan4e641df2013-11-03 16:54:46 +1000355 self.test_exe = exe = os.path.join(exepath, exename)
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000356 if not os.path.exists(exe):
357 self.skipTest("%r doesn't exist" % exe)
Antoine Pitrou8e605772011-04-25 21:21:07 +0200358 # This is needed otherwise we get a fatal error:
359 # "Py_Initialize: Unable to get the locale encoding
360 # LookupError: no codec search functions registered: can't find encoding"
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000361 self.oldcwd = os.getcwd()
Antoine Pitrou8e605772011-04-25 21:21:07 +0200362 os.chdir(basepath)
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000363
364 def tearDown(self):
365 os.chdir(self.oldcwd)
366
367 def run_embedded_interpreter(self, *args):
368 """Runs a test in the embedded interpreter"""
369 cmd = [self.test_exe]
370 cmd.extend(args)
371 p = subprocess.Popen(cmd,
372 stdout=subprocess.PIPE,
Steve Dower86e9deb2014-11-01 15:11:05 -0700373 stderr=subprocess.PIPE,
374 universal_newlines=True)
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000375 (out, err) = p.communicate()
376 self.assertEqual(p.returncode, 0,
377 "bad returncode %d, stderr is %r" %
378 (p.returncode, err))
Steve Dower86e9deb2014-11-01 15:11:05 -0700379 return out, err
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000380
381 def test_subinterps(self):
382 # This is just a "don't crash" test
383 out, err = self.run_embedded_interpreter()
384 if support.verbose:
385 print()
386 print(out)
387 print(err)
388
Nick Coghlan4e641df2013-11-03 16:54:46 +1000389 @staticmethod
390 def _get_default_pipe_encoding():
391 rp, wp = os.pipe()
392 try:
393 with os.fdopen(wp, 'w') as w:
394 default_pipe_encoding = w.encoding
395 finally:
396 os.close(rp)
397 return default_pipe_encoding
398
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000399 def test_forced_io_encoding(self):
400 # Checks forced configuration of embedded interpreter IO streams
401 out, err = self.run_embedded_interpreter("forced_io_encoding")
402 if support.verbose:
403 print()
404 print(out)
405 print(err)
Victor Stinnerb2bef622014-03-18 02:38:12 +0100406 expected_errors = sys.__stdout__.errors
Nick Coghlan4e641df2013-11-03 16:54:46 +1000407 expected_stdin_encoding = sys.__stdin__.encoding
408 expected_pipe_encoding = self._get_default_pipe_encoding()
Steve Dower86e9deb2014-11-01 15:11:05 -0700409 expected_output = '\n'.join([
Nick Coghlan4e641df2013-11-03 16:54:46 +1000410 "--- Use defaults ---",
411 "Expected encoding: default",
412 "Expected errors: default",
Victor Stinnerb2bef622014-03-18 02:38:12 +0100413 "stdin: {in_encoding}:{errors}",
414 "stdout: {out_encoding}:{errors}",
415 "stderr: {out_encoding}:backslashreplace",
Nick Coghlan4e641df2013-11-03 16:54:46 +1000416 "--- Set errors only ---",
417 "Expected encoding: default",
Victor Stinnerb2bef622014-03-18 02:38:12 +0100418 "Expected errors: ignore",
419 "stdin: {in_encoding}:ignore",
420 "stdout: {out_encoding}:ignore",
421 "stderr: {out_encoding}:backslashreplace",
Nick Coghlan4e641df2013-11-03 16:54:46 +1000422 "--- Set encoding only ---",
423 "Expected encoding: latin-1",
424 "Expected errors: default",
Victor Stinnerb2bef622014-03-18 02:38:12 +0100425 "stdin: latin-1:{errors}",
426 "stdout: latin-1:{errors}",
Nick Coghlan4e641df2013-11-03 16:54:46 +1000427 "stderr: latin-1:backslashreplace",
428 "--- Set encoding and errors ---",
429 "Expected encoding: latin-1",
Victor Stinnerb2bef622014-03-18 02:38:12 +0100430 "Expected errors: replace",
431 "stdin: latin-1:replace",
432 "stdout: latin-1:replace",
433 "stderr: latin-1:backslashreplace"])
434 expected_output = expected_output.format(
435 in_encoding=expected_stdin_encoding,
436 out_encoding=expected_pipe_encoding,
437 errors=expected_errors)
Nick Coghlan3321fb82013-10-18 23:59:58 +1000438 # This is useful if we ever trip over odd platform behaviour
Nick Coghlan6508dc52013-10-18 01:44:22 +1000439 self.maxDiff = None
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000440 self.assertEqual(out.strip(), expected_output)
Antoine Pitrou8e605772011-04-25 21:21:07 +0200441
Larry Hastings8f904da2012-06-22 03:56:29 -0700442class SkipitemTest(unittest.TestCase):
443
444 def test_skipitem(self):
445 """
446 If this test failed, you probably added a new "format unit"
447 in Python/getargs.c, but neglected to update our poor friend
448 skipitem() in the same file. (If so, shame on you!)
449
Larry Hastings48ed3602012-06-22 12:58:36 -0700450 With a few exceptions**, this function brute-force tests all
451 printable ASCII*** characters (32 to 126 inclusive) as format units,
452 checking to see that PyArg_ParseTupleAndKeywords() return consistent
453 errors both when the unit is attempted to be used and when it is
454 skipped. If the format unit doesn't exist, we'll get one of two
455 specific error messages (one for used, one for skipped); if it does
456 exist we *won't* get that error--we'll get either no error or some
457 other error. If we get the specific "does not exist" error for one
458 test and not for the other, there's a mismatch, and the test fails.
Larry Hastings8f904da2012-06-22 03:56:29 -0700459
Larry Hastings48ed3602012-06-22 12:58:36 -0700460 ** Some format units have special funny semantics and it would
461 be difficult to accomodate them here. Since these are all
462 well-established and properly skipped in skipitem() we can
463 get away with not testing them--this test is really intended
464 to catch *new* format units.
465
466 *** Python C source files must be ASCII. Therefore it's impossible
467 to have non-ASCII format units.
468
Larry Hastings8f904da2012-06-22 03:56:29 -0700469 """
470 empty_tuple = ()
471 tuple_1 = (0,)
472 dict_b = {'b':1}
473 keywords = ["a", "b"]
474
Larry Hastings48ed3602012-06-22 12:58:36 -0700475 for i in range(32, 127):
Larry Hastings8f904da2012-06-22 03:56:29 -0700476 c = chr(i)
477
Larry Hastings8f904da2012-06-22 03:56:29 -0700478 # skip parentheses, the error reporting is inconsistent about them
479 # skip 'e', it's always a two-character code
480 # skip '|' and '$', they don't represent arguments anyway
Larry Hastings48ed3602012-06-22 12:58:36 -0700481 if c in '()e|$':
Larry Hastings8f904da2012-06-22 03:56:29 -0700482 continue
483
484 # test the format unit when not skipped
485 format = c + "i"
486 try:
487 # (note: the format string must be bytes!)
488 _testcapi.parse_tuple_and_keywords(tuple_1, dict_b,
489 format.encode("ascii"), keywords)
490 when_not_skipped = False
Serhiy Storchaka4cd63ef2016-02-08 01:22:47 +0200491 except SystemError as e:
Serhiy Storchakac4b813d2016-02-08 01:06:11 +0200492 s = "argument 1 (impossible<bad format char>)"
Larry Hastings8f904da2012-06-22 03:56:29 -0700493 when_not_skipped = (str(e) == s)
Serhiy Storchakaa9725f82016-02-11 12:41:40 +0200494 except TypeError:
Larry Hastings8f904da2012-06-22 03:56:29 -0700495 when_not_skipped = False
496
497 # test the format unit when skipped
498 optional_format = "|" + format
499 try:
500 _testcapi.parse_tuple_and_keywords(empty_tuple, dict_b,
501 optional_format.encode("ascii"), keywords)
502 when_skipped = False
Serhiy Storchakaa9725f82016-02-11 12:41:40 +0200503 except SystemError as e:
Larry Hastings8f904da2012-06-22 03:56:29 -0700504 s = "impossible<bad format char>: '{}'".format(format)
505 when_skipped = (str(e) == s)
506
507 message = ("test_skipitem_parity: "
508 "detected mismatch between convertsimple and skipitem "
509 "for format unit '{}' ({}), not skipped {}, skipped {}".format(
510 c, i, when_skipped, when_not_skipped))
511 self.assertIs(when_skipped, when_not_skipped, message)
Antoine Pitrou8e605772011-04-25 21:21:07 +0200512
Jesus Cea6e1d2b62012-10-04 16:06:30 +0200513 def test_parse_tuple_and_keywords(self):
514 # parse_tuple_and_keywords error handling tests
515 self.assertRaises(TypeError, _testcapi.parse_tuple_and_keywords,
516 (), {}, 42, [])
517 self.assertRaises(ValueError, _testcapi.parse_tuple_and_keywords,
518 (), {}, b'', 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
Ezio Melotti29267c82013-02-23 05:52:46 +0200524@unittest.skipUnless(threading, 'Threading required for this test.')
525class TestThreadState(unittest.TestCase):
526
527 @support.reap_threads
528 def test_thread_state(self):
529 # some extra thread-state tests driven via _testcapi
530 def target():
531 idents = []
532
533 def callback():
Ezio Melotti35246bd2013-02-23 05:58:38 +0200534 idents.append(threading.get_ident())
Ezio Melotti29267c82013-02-23 05:52:46 +0200535
536 _testcapi._test_thread_state(callback)
537 a = b = callback
538 time.sleep(1)
539 # Check our main thread is in the list exactly 3 times.
Ezio Melotti35246bd2013-02-23 05:58:38 +0200540 self.assertEqual(idents.count(threading.get_ident()), 3,
Ezio Melotti29267c82013-02-23 05:52:46 +0200541 "Couldn't find main thread correctly in the list")
542
543 target()
544 t = threading.Thread(target=target)
545 t.start()
546 t.join()
547
Zachary Warec12f09e2013-11-11 22:47:04 -0600548class Test_testcapi(unittest.TestCase):
549 def test__testcapi(self):
550 for name in dir(_testcapi):
551 if name.startswith('test_'):
Zachary Waredfcd6942013-11-11 22:59:23 -0600552 with self.subTest("internal", name=name):
553 test = getattr(_testcapi, name)
554 test()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000555
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000556if __name__ == "__main__":
Zachary Warec12f09e2013-11-11 22:47:04 -0600557 unittest.main()