blob: de8d65a963ce4d1feddca0e3ec711dae5f660f52 [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
Benjamin Petersona54c9092009-01-13 02:11:23 +00009import time
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000010import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +000011from test import support
Larry Hastingsfcafe432013-11-23 17:35:48 -080012from test.support import MISSING_C_DOCSTRINGS
Victor Stinner45df8202010-04-28 22:31:17 +000013try:
Stefan Krahfd24f9e2012-08-20 11:04:24 +020014 import _posixsubprocess
15except ImportError:
16 _posixsubprocess = None
17try:
Victor Stinner45df8202010-04-28 22:31:17 +000018 import threading
19except ImportError:
20 threading = None
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +020021# Skip this test if the _testcapi module isn't available.
22_testcapi = support.import_module('_testcapi')
Tim Peters9ea17ac2001-02-02 05:57:15 +000023
Benjamin Petersona54c9092009-01-13 02:11:23 +000024
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000025def testfunction(self):
26 """some doc"""
27 return self
28
29class InstanceMethod:
30 id = _testcapi.instancemethod(id)
31 testfunction = _testcapi.instancemethod(testfunction)
32
33class CAPITest(unittest.TestCase):
34
35 def test_instancemethod(self):
36 inst = InstanceMethod()
37 self.assertEqual(id(inst), inst.id())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000038 self.assertTrue(inst.testfunction() is inst)
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000039 self.assertEqual(inst.testfunction.__doc__, testfunction.__doc__)
40 self.assertEqual(InstanceMethod.testfunction.__doc__, testfunction.__doc__)
41
42 InstanceMethod.testfunction.attribute = "test"
43 self.assertEqual(testfunction.attribute, "test")
44 self.assertRaises(AttributeError, setattr, inst.testfunction, "attribute", "test")
45
Stefan Krah0ca46242010-06-09 08:56:28 +000046 @unittest.skipUnless(threading, 'Threading required for this test.')
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000047 def test_no_FatalError_infinite_loop(self):
Antoine Pitrou77e904e2013-10-08 23:04:32 +020048 with support.SuppressCrashReport():
Ezio Melotti25a40452013-03-05 20:26:17 +020049 p = subprocess.Popen([sys.executable, "-c",
Ezio Melottie1857d92013-03-05 20:31:34 +020050 'import _testcapi;'
51 '_testcapi.crash_no_current_thread()'],
52 stdout=subprocess.PIPE,
53 stderr=subprocess.PIPE)
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000054 (out, err) = p.communicate()
55 self.assertEqual(out, b'')
56 # This used to cause an infinite loop.
Vinay Sajip73954042012-05-06 11:34:50 +010057 self.assertTrue(err.rstrip().startswith(
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000058 b'Fatal Python error:'
Vinay Sajip73954042012-05-06 11:34:50 +010059 b' PyThreadState_Get: no current thread'))
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000060
Antoine Pitrou915605c2011-02-24 20:53:48 +000061 def test_memoryview_from_NULL_pointer(self):
62 self.assertRaises(ValueError, _testcapi.make_memoryview_from_NULL_pointer)
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000063
Martin v. Löwisaa2efcb2012-04-19 14:33:43 +020064 def test_exc_info(self):
65 raised_exception = ValueError("5")
66 new_exc = TypeError("TEST")
67 try:
68 raise raised_exception
69 except ValueError as e:
70 tb = e.__traceback__
71 orig_sys_exc_info = sys.exc_info()
72 orig_exc_info = _testcapi.set_exc_info(new_exc.__class__, new_exc, None)
73 new_sys_exc_info = sys.exc_info()
74 new_exc_info = _testcapi.set_exc_info(*orig_exc_info)
75 reset_sys_exc_info = sys.exc_info()
76
77 self.assertEqual(orig_exc_info[1], e)
78
79 self.assertSequenceEqual(orig_exc_info, (raised_exception.__class__, raised_exception, tb))
80 self.assertSequenceEqual(orig_sys_exc_info, orig_exc_info)
81 self.assertSequenceEqual(reset_sys_exc_info, orig_exc_info)
82 self.assertSequenceEqual(new_exc_info, (new_exc.__class__, new_exc, None))
83 self.assertSequenceEqual(new_sys_exc_info, new_exc_info)
84 else:
85 self.assertTrue(False)
86
Stefan Krahfd24f9e2012-08-20 11:04:24 +020087 @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
88 def test_seq_bytes_to_charp_array(self):
89 # Issue #15732: crash in _PySequence_BytesToCharpArray()
90 class Z(object):
91 def __len__(self):
92 return 1
93 self.assertRaises(TypeError, _posixsubprocess.fork_exec,
94 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 +020095 # Issue #15736: overflow in _PySequence_BytesToCharpArray()
96 class Z(object):
97 def __len__(self):
98 return sys.maxsize
99 def __getitem__(self, i):
100 return b'x'
101 self.assertRaises(MemoryError, _posixsubprocess.fork_exec,
102 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 +0200103
Stefan Krahdb579d72012-08-20 14:36:47 +0200104 @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
105 def test_subprocess_fork_exec(self):
106 class Z(object):
107 def __len__(self):
108 return 1
109
110 # Issue #15738: crash in subprocess_fork_exec()
111 self.assertRaises(TypeError, _posixsubprocess.fork_exec,
112 Z(),[b'1'],3,[1, 2],5,6,7,8,9,10,11,12,13,14,15,16,17)
113
Larry Hastingsfcafe432013-11-23 17:35:48 -0800114 @unittest.skipIf(MISSING_C_DOCSTRINGS,
115 "Signature information for builtins requires docstrings")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800116 def test_docstring_signature_parsing(self):
117
118 self.assertEqual(_testcapi.no_docstring.__doc__, None)
119 self.assertEqual(_testcapi.no_docstring.__text_signature__, None)
120
121 self.assertEqual(_testcapi.docstring_empty.__doc__, "")
122 self.assertEqual(_testcapi.docstring_empty.__text_signature__, None)
123
124 self.assertEqual(_testcapi.docstring_no_signature.__doc__,
125 "This docstring has no signature.")
126 self.assertEqual(_testcapi.docstring_no_signature.__text_signature__, None)
127
128 self.assertEqual(_testcapi.docstring_with_invalid_signature.__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800129 "docstring_with_invalid_signature($module, /, boo)\n"
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800130 "\n"
131 "This docstring has an invalid signature."
132 )
133 self.assertEqual(_testcapi.docstring_with_invalid_signature.__text_signature__, None)
134
Larry Hastings2623c8c2014-02-08 22:15:29 -0800135 self.assertEqual(_testcapi.docstring_with_invalid_signature2.__doc__,
136 "docstring_with_invalid_signature2($module, /, boo)\n"
137 "\n"
138 "--\n"
139 "\n"
140 "This docstring also has an invalid signature."
141 )
142 self.assertEqual(_testcapi.docstring_with_invalid_signature2.__text_signature__, None)
143
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800144 self.assertEqual(_testcapi.docstring_with_signature.__doc__,
145 "This docstring has a valid signature.")
Larry Hastings2623c8c2014-02-08 22:15:29 -0800146 self.assertEqual(_testcapi.docstring_with_signature.__text_signature__, "($module, /, sig)")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800147
148 self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800149 "\nThis docstring has a valid signature and some extra newlines.")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800150 self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__text_signature__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800151 "($module, /, parameter)")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800152
Benjamin Petersond51374e2014-04-09 23:55:56 -0400153 def test_c_type_with_matrix_multiplication(self):
154 M = _testcapi.matmulType
155 m1 = M()
156 m2 = M()
157 self.assertEqual(m1 @ m2, ("matmul", m1, m2))
158 self.assertEqual(m1 @ 42, ("matmul", m1, 42))
159 self.assertEqual(42 @ m1, ("matmul", 42, m1))
160 o = m1
161 o @= m2
162 self.assertEqual(o, ("imatmul", m1, m2))
163 o = m1
164 o @= 42
165 self.assertEqual(o, ("imatmul", m1, 42))
166 o = 42
167 o @= m1
168 self.assertEqual(o, ("matmul", 42, m1))
169
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800170
Victor Stinner45df8202010-04-28 22:31:17 +0000171@unittest.skipUnless(threading, 'Threading required for this test.')
Benjamin Petersona54c9092009-01-13 02:11:23 +0000172class TestPendingCalls(unittest.TestCase):
173
174 def pendingcalls_submit(self, l, n):
175 def callback():
176 #this function can be interrupted by thread switching so let's
177 #use an atomic operation
178 l.append(None)
179
180 for i in range(n):
181 time.sleep(random.random()*0.02) #0.01 secs on average
182 #try submitting callback until successful.
183 #rely on regular interrupt to flush queue if we are
184 #unsuccessful.
185 while True:
186 if _testcapi._pending_threadfunc(callback):
187 break;
188
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000189 def pendingcalls_wait(self, l, n, context = None):
Benjamin Petersona54c9092009-01-13 02:11:23 +0000190 #now, stick around until l[0] has grown to 10
191 count = 0;
192 while len(l) != n:
193 #this busy loop is where we expect to be interrupted to
194 #run our callbacks. Note that callbacks are only run on the
195 #main thread
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000196 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +0000197 print("(%i)"%(len(l),),)
198 for i in range(1000):
199 a = i*i
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000200 if context and not context.event.is_set():
201 continue
Benjamin Petersona54c9092009-01-13 02:11:23 +0000202 count += 1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000203 self.assertTrue(count < 10000,
Benjamin Petersona54c9092009-01-13 02:11:23 +0000204 "timeout waiting for %i callbacks, got %i"%(n, len(l)))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000205 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +0000206 print("(%i)"%(len(l),))
207
208 def test_pendingcalls_threaded(self):
Benjamin Petersona54c9092009-01-13 02:11:23 +0000209
210 #do every callback on a separate thread
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000211 n = 32 #total callbacks
Benjamin Petersona54c9092009-01-13 02:11:23 +0000212 threads = []
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000213 class foo(object):pass
214 context = foo()
215 context.l = []
216 context.n = 2 #submits per thread
217 context.nThreads = n // context.n
218 context.nFinished = 0
219 context.lock = threading.Lock()
220 context.event = threading.Event()
221
222 for i in range(context.nThreads):
223 t = threading.Thread(target=self.pendingcalls_thread, args = (context,))
Benjamin Petersona54c9092009-01-13 02:11:23 +0000224 t.start()
225 threads.append(t)
226
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000227 self.pendingcalls_wait(context.l, n, context)
Benjamin Petersona54c9092009-01-13 02:11:23 +0000228
229 for t in threads:
230 t.join()
231
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000232 def pendingcalls_thread(self, context):
233 try:
234 self.pendingcalls_submit(context.l, context.n)
235 finally:
236 with context.lock:
237 context.nFinished += 1
238 nFinished = context.nFinished
239 if False and support.verbose:
240 print("finished threads: ", nFinished)
241 if nFinished == context.nThreads:
242 context.event.set()
243
Benjamin Petersona54c9092009-01-13 02:11:23 +0000244 def test_pendingcalls_non_threaded(self):
Ezio Melotti13925002011-03-16 11:05:33 +0200245 #again, just using the main thread, likely they will all be dispatched at
Benjamin Petersona54c9092009-01-13 02:11:23 +0000246 #once. It is ok to ask for too many, because we loop until we find a slot.
247 #the loop can be interrupted to dispatch.
248 #there are only 32 dispatch slots, so we go for twice that!
249 l = []
250 n = 64
251 self.pendingcalls_submit(l, n)
252 self.pendingcalls_wait(l, n)
253
Antoine Pitrou7a2572c2013-08-01 20:43:26 +0200254
255class SubinterpreterTest(unittest.TestCase):
256
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100257 def test_subinterps(self):
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100258 import builtins
259 r, w = os.pipe()
260 code = """if 1:
261 import sys, builtins, pickle
262 with open({:d}, "wb") as f:
263 pickle.dump(id(sys.modules), f)
264 pickle.dump(id(builtins), f)
265 """.format(w)
266 with open(r, "rb") as f:
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100267 ret = support.run_in_subinterp(code)
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100268 self.assertEqual(ret, 0)
269 self.assertNotEqual(pickle.load(f), id(sys.modules))
270 self.assertNotEqual(pickle.load(f), id(builtins))
271
Antoine Pitrou7a2572c2013-08-01 20:43:26 +0200272
Martin v. Löwisc15bdef2009-05-29 14:47:46 +0000273# Bug #6012
274class Test6012(unittest.TestCase):
275 def test(self):
276 self.assertEqual(_testcapi.argparsing("Hello", "World"), 1)
Benjamin Petersona54c9092009-01-13 02:11:23 +0000277
Antoine Pitrou8e605772011-04-25 21:21:07 +0200278
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000279class EmbeddingTests(unittest.TestCase):
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000280 def setUp(self):
Antoine Pitrou8e605772011-04-25 21:21:07 +0200281 basepath = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
Nick Coghlan4e641df2013-11-03 16:54:46 +1000282 exename = "_testembed"
283 if sys.platform.startswith("win"):
284 ext = ("_d" if "_d" in sys.executable else "") + ".exe"
285 exename += ext
286 exepath = os.path.dirname(sys.executable)
287 else:
Nick Coghlanbca9acf2014-09-25 19:48:15 +1000288 exepath = os.path.join(basepath, "Programs")
Nick Coghlan4e641df2013-11-03 16:54:46 +1000289 self.test_exe = exe = os.path.join(exepath, exename)
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000290 if not os.path.exists(exe):
291 self.skipTest("%r doesn't exist" % exe)
Antoine Pitrou8e605772011-04-25 21:21:07 +0200292 # This is needed otherwise we get a fatal error:
293 # "Py_Initialize: Unable to get the locale encoding
294 # LookupError: no codec search functions registered: can't find encoding"
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000295 self.oldcwd = os.getcwd()
Antoine Pitrou8e605772011-04-25 21:21:07 +0200296 os.chdir(basepath)
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000297
298 def tearDown(self):
299 os.chdir(self.oldcwd)
300
301 def run_embedded_interpreter(self, *args):
302 """Runs a test in the embedded interpreter"""
303 cmd = [self.test_exe]
304 cmd.extend(args)
305 p = subprocess.Popen(cmd,
306 stdout=subprocess.PIPE,
Steve Dower86e9deb2014-11-01 15:11:05 -0700307 stderr=subprocess.PIPE,
308 universal_newlines=True)
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000309 (out, err) = p.communicate()
310 self.assertEqual(p.returncode, 0,
311 "bad returncode %d, stderr is %r" %
312 (p.returncode, err))
Steve Dower86e9deb2014-11-01 15:11:05 -0700313 return out, err
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000314
315 def test_subinterps(self):
316 # This is just a "don't crash" test
317 out, err = self.run_embedded_interpreter()
318 if support.verbose:
319 print()
320 print(out)
321 print(err)
322
Nick Coghlan4e641df2013-11-03 16:54:46 +1000323 @staticmethod
324 def _get_default_pipe_encoding():
325 rp, wp = os.pipe()
326 try:
327 with os.fdopen(wp, 'w') as w:
328 default_pipe_encoding = w.encoding
329 finally:
330 os.close(rp)
331 return default_pipe_encoding
332
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000333 def test_forced_io_encoding(self):
334 # Checks forced configuration of embedded interpreter IO streams
335 out, err = self.run_embedded_interpreter("forced_io_encoding")
336 if support.verbose:
337 print()
338 print(out)
339 print(err)
Victor Stinnerb2bef622014-03-18 02:38:12 +0100340 expected_errors = sys.__stdout__.errors
Nick Coghlan4e641df2013-11-03 16:54:46 +1000341 expected_stdin_encoding = sys.__stdin__.encoding
342 expected_pipe_encoding = self._get_default_pipe_encoding()
Steve Dower86e9deb2014-11-01 15:11:05 -0700343 expected_output = '\n'.join([
Nick Coghlan4e641df2013-11-03 16:54:46 +1000344 "--- Use defaults ---",
345 "Expected encoding: default",
346 "Expected errors: default",
Victor Stinnerb2bef622014-03-18 02:38:12 +0100347 "stdin: {in_encoding}:{errors}",
348 "stdout: {out_encoding}:{errors}",
349 "stderr: {out_encoding}:backslashreplace",
Nick Coghlan4e641df2013-11-03 16:54:46 +1000350 "--- Set errors only ---",
351 "Expected encoding: default",
Victor Stinnerb2bef622014-03-18 02:38:12 +0100352 "Expected errors: ignore",
353 "stdin: {in_encoding}:ignore",
354 "stdout: {out_encoding}:ignore",
355 "stderr: {out_encoding}:backslashreplace",
Nick Coghlan4e641df2013-11-03 16:54:46 +1000356 "--- Set encoding only ---",
357 "Expected encoding: latin-1",
358 "Expected errors: default",
Victor Stinnerb2bef622014-03-18 02:38:12 +0100359 "stdin: latin-1:{errors}",
360 "stdout: latin-1:{errors}",
Nick Coghlan4e641df2013-11-03 16:54:46 +1000361 "stderr: latin-1:backslashreplace",
362 "--- Set encoding and errors ---",
363 "Expected encoding: latin-1",
Victor Stinnerb2bef622014-03-18 02:38:12 +0100364 "Expected errors: replace",
365 "stdin: latin-1:replace",
366 "stdout: latin-1:replace",
367 "stderr: latin-1:backslashreplace"])
368 expected_output = expected_output.format(
369 in_encoding=expected_stdin_encoding,
370 out_encoding=expected_pipe_encoding,
371 errors=expected_errors)
Nick Coghlan3321fb82013-10-18 23:59:58 +1000372 # This is useful if we ever trip over odd platform behaviour
Nick Coghlan6508dc52013-10-18 01:44:22 +1000373 self.maxDiff = None
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000374 self.assertEqual(out.strip(), expected_output)
Antoine Pitrou8e605772011-04-25 21:21:07 +0200375
Larry Hastings8f904da2012-06-22 03:56:29 -0700376class SkipitemTest(unittest.TestCase):
377
378 def test_skipitem(self):
379 """
380 If this test failed, you probably added a new "format unit"
381 in Python/getargs.c, but neglected to update our poor friend
382 skipitem() in the same file. (If so, shame on you!)
383
Larry Hastings48ed3602012-06-22 12:58:36 -0700384 With a few exceptions**, this function brute-force tests all
385 printable ASCII*** characters (32 to 126 inclusive) as format units,
386 checking to see that PyArg_ParseTupleAndKeywords() return consistent
387 errors both when the unit is attempted to be used and when it is
388 skipped. If the format unit doesn't exist, we'll get one of two
389 specific error messages (one for used, one for skipped); if it does
390 exist we *won't* get that error--we'll get either no error or some
391 other error. If we get the specific "does not exist" error for one
392 test and not for the other, there's a mismatch, and the test fails.
Larry Hastings8f904da2012-06-22 03:56:29 -0700393
Larry Hastings48ed3602012-06-22 12:58:36 -0700394 ** Some format units have special funny semantics and it would
395 be difficult to accomodate them here. Since these are all
396 well-established and properly skipped in skipitem() we can
397 get away with not testing them--this test is really intended
398 to catch *new* format units.
399
400 *** Python C source files must be ASCII. Therefore it's impossible
401 to have non-ASCII format units.
402
Larry Hastings8f904da2012-06-22 03:56:29 -0700403 """
404 empty_tuple = ()
405 tuple_1 = (0,)
406 dict_b = {'b':1}
407 keywords = ["a", "b"]
408
Larry Hastings48ed3602012-06-22 12:58:36 -0700409 for i in range(32, 127):
Larry Hastings8f904da2012-06-22 03:56:29 -0700410 c = chr(i)
411
Larry Hastings8f904da2012-06-22 03:56:29 -0700412 # skip parentheses, the error reporting is inconsistent about them
413 # skip 'e', it's always a two-character code
414 # skip '|' and '$', they don't represent arguments anyway
Larry Hastings48ed3602012-06-22 12:58:36 -0700415 if c in '()e|$':
Larry Hastings8f904da2012-06-22 03:56:29 -0700416 continue
417
418 # test the format unit when not skipped
419 format = c + "i"
420 try:
421 # (note: the format string must be bytes!)
422 _testcapi.parse_tuple_and_keywords(tuple_1, dict_b,
423 format.encode("ascii"), keywords)
424 when_not_skipped = False
425 except TypeError as e:
426 s = "argument 1 must be impossible<bad format char>, not int"
427 when_not_skipped = (str(e) == s)
428 except RuntimeError as e:
429 when_not_skipped = False
430
431 # test the format unit when skipped
432 optional_format = "|" + format
433 try:
434 _testcapi.parse_tuple_and_keywords(empty_tuple, dict_b,
435 optional_format.encode("ascii"), keywords)
436 when_skipped = False
437 except RuntimeError as e:
438 s = "impossible<bad format char>: '{}'".format(format)
439 when_skipped = (str(e) == s)
440
441 message = ("test_skipitem_parity: "
442 "detected mismatch between convertsimple and skipitem "
443 "for format unit '{}' ({}), not skipped {}, skipped {}".format(
444 c, i, when_skipped, when_not_skipped))
445 self.assertIs(when_skipped, when_not_skipped, message)
Antoine Pitrou8e605772011-04-25 21:21:07 +0200446
Jesus Cea6e1d2b62012-10-04 16:06:30 +0200447 def test_parse_tuple_and_keywords(self):
448 # parse_tuple_and_keywords error handling tests
449 self.assertRaises(TypeError, _testcapi.parse_tuple_and_keywords,
450 (), {}, 42, [])
451 self.assertRaises(ValueError, _testcapi.parse_tuple_and_keywords,
452 (), {}, b'', 42)
453 self.assertRaises(ValueError, _testcapi.parse_tuple_and_keywords,
454 (), {}, b'', [''] * 42)
455 self.assertRaises(ValueError, _testcapi.parse_tuple_and_keywords,
456 (), {}, b'', [42])
457
Ezio Melotti29267c82013-02-23 05:52:46 +0200458@unittest.skipUnless(threading, 'Threading required for this test.')
459class TestThreadState(unittest.TestCase):
460
461 @support.reap_threads
462 def test_thread_state(self):
463 # some extra thread-state tests driven via _testcapi
464 def target():
465 idents = []
466
467 def callback():
Ezio Melotti35246bd2013-02-23 05:58:38 +0200468 idents.append(threading.get_ident())
Ezio Melotti29267c82013-02-23 05:52:46 +0200469
470 _testcapi._test_thread_state(callback)
471 a = b = callback
472 time.sleep(1)
473 # Check our main thread is in the list exactly 3 times.
Ezio Melotti35246bd2013-02-23 05:58:38 +0200474 self.assertEqual(idents.count(threading.get_ident()), 3,
Ezio Melotti29267c82013-02-23 05:52:46 +0200475 "Couldn't find main thread correctly in the list")
476
477 target()
478 t = threading.Thread(target=target)
479 t.start()
480 t.join()
481
Zachary Warec12f09e2013-11-11 22:47:04 -0600482class Test_testcapi(unittest.TestCase):
483 def test__testcapi(self):
484 for name in dir(_testcapi):
485 if name.startswith('test_'):
Zachary Waredfcd6942013-11-11 22:59:23 -0600486 with self.subTest("internal", name=name):
487 test = getattr(_testcapi, name)
488 test()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000489
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000490if __name__ == "__main__":
Zachary Warec12f09e2013-11-11 22:47:04 -0600491 unittest.main()