blob: 0ab145807e14387cd8a7aa53bd7f53be9bc1ba60 [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
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00004from __future__ import with_statement
Antoine Pitrou8e605772011-04-25 21:21:07 +02005import os
Antoine Pitrou2f828f22012-01-18 00:21:11 +01006import pickle
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +00007import random
8import subprocess
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00009import sys
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
Victor Stinner45df8202010-04-28 22:31:17 +000013try:
Stefan Krahfd24f9e2012-08-20 11:04:24 +020014 import _posixsubprocess
15except ImportError:
16 _posixsubprocess = None
17try:
Ezio Melotti1ca87942013-02-23 06:42:19 +020018 import _thread
Victor Stinner45df8202010-04-28 22:31:17 +000019 import threading
20except ImportError:
Ezio Melotti1ca87942013-02-23 06:42:19 +020021 _thread = None
Victor Stinner45df8202010-04-28 22:31:17 +000022 threading = None
Tim Petersd66595f2001-02-04 03:09:53 +000023import _testcapi
Tim Peters9ea17ac2001-02-02 05:57:15 +000024
Benjamin Petersona54c9092009-01-13 02:11:23 +000025
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000026def testfunction(self):
27 """some doc"""
28 return self
29
30class InstanceMethod:
31 id = _testcapi.instancemethod(id)
32 testfunction = _testcapi.instancemethod(testfunction)
33
34class CAPITest(unittest.TestCase):
35
36 def test_instancemethod(self):
37 inst = InstanceMethod()
38 self.assertEqual(id(inst), inst.id())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000039 self.assertTrue(inst.testfunction() is inst)
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000040 self.assertEqual(inst.testfunction.__doc__, testfunction.__doc__)
41 self.assertEqual(InstanceMethod.testfunction.__doc__, testfunction.__doc__)
42
43 InstanceMethod.testfunction.attribute = "test"
44 self.assertEqual(testfunction.attribute, "test")
45 self.assertRaises(AttributeError, setattr, inst.testfunction, "attribute", "test")
46
Stefan Krah0ca46242010-06-09 08:56:28 +000047 @unittest.skipUnless(threading, 'Threading required for this test.')
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000048 def test_no_FatalError_infinite_loop(self):
49 p = subprocess.Popen([sys.executable, "-c",
50 'import _testcapi;'
51 '_testcapi.crash_no_current_thread()'],
52 stdout=subprocess.PIPE,
53 stderr=subprocess.PIPE)
54 (out, err) = p.communicate()
55 self.assertEqual(out, b'')
56 # This used to cause an infinite loop.
Victor Stinner4000ffa2010-05-15 01:40:41 +000057 self.assertEqual(err.rstrip(),
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000058 b'Fatal Python error:'
Victor Stinner4000ffa2010-05-15 01:40:41 +000059 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
Stefan Krahfd24f9e2012-08-20 11:04:24 +020064 @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
65 def test_seq_bytes_to_charp_array(self):
66 # Issue #15732: crash in _PySequence_BytesToCharpArray()
67 class Z(object):
68 def __len__(self):
69 return 1
70 self.assertRaises(TypeError, _posixsubprocess.fork_exec,
71 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 +020072 # Issue #15736: overflow in _PySequence_BytesToCharpArray()
73 class Z(object):
74 def __len__(self):
75 return sys.maxsize
76 def __getitem__(self, i):
77 return b'x'
78 self.assertRaises(MemoryError, _posixsubprocess.fork_exec,
79 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 +020080
Stefan Krahdb579d72012-08-20 14:36:47 +020081 @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
82 def test_subprocess_fork_exec(self):
83 class Z(object):
84 def __len__(self):
85 return 1
86
87 # Issue #15738: crash in subprocess_fork_exec()
88 self.assertRaises(TypeError, _posixsubprocess.fork_exec,
89 Z(),[b'1'],3,[1, 2],5,6,7,8,9,10,11,12,13,14,15,16,17)
90
Victor Stinner45df8202010-04-28 22:31:17 +000091@unittest.skipUnless(threading, 'Threading required for this test.')
Benjamin Petersona54c9092009-01-13 02:11:23 +000092class TestPendingCalls(unittest.TestCase):
93
94 def pendingcalls_submit(self, l, n):
95 def callback():
96 #this function can be interrupted by thread switching so let's
97 #use an atomic operation
98 l.append(None)
99
100 for i in range(n):
101 time.sleep(random.random()*0.02) #0.01 secs on average
102 #try submitting callback until successful.
103 #rely on regular interrupt to flush queue if we are
104 #unsuccessful.
105 while True:
106 if _testcapi._pending_threadfunc(callback):
107 break;
108
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000109 def pendingcalls_wait(self, l, n, context = None):
Benjamin Petersona54c9092009-01-13 02:11:23 +0000110 #now, stick around until l[0] has grown to 10
111 count = 0;
112 while len(l) != n:
113 #this busy loop is where we expect to be interrupted to
114 #run our callbacks. Note that callbacks are only run on the
115 #main thread
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000116 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +0000117 print("(%i)"%(len(l),),)
118 for i in range(1000):
119 a = i*i
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000120 if context and not context.event.is_set():
121 continue
Benjamin Petersona54c9092009-01-13 02:11:23 +0000122 count += 1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000123 self.assertTrue(count < 10000,
Benjamin Petersona54c9092009-01-13 02:11:23 +0000124 "timeout waiting for %i callbacks, got %i"%(n, len(l)))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000125 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +0000126 print("(%i)"%(len(l),))
127
128 def test_pendingcalls_threaded(self):
Benjamin Petersona54c9092009-01-13 02:11:23 +0000129
130 #do every callback on a separate thread
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000131 n = 32 #total callbacks
Benjamin Petersona54c9092009-01-13 02:11:23 +0000132 threads = []
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000133 class foo(object):pass
134 context = foo()
135 context.l = []
136 context.n = 2 #submits per thread
137 context.nThreads = n // context.n
138 context.nFinished = 0
139 context.lock = threading.Lock()
140 context.event = threading.Event()
141
142 for i in range(context.nThreads):
143 t = threading.Thread(target=self.pendingcalls_thread, args = (context,))
Benjamin Petersona54c9092009-01-13 02:11:23 +0000144 t.start()
145 threads.append(t)
146
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000147 self.pendingcalls_wait(context.l, n, context)
Benjamin Petersona54c9092009-01-13 02:11:23 +0000148
149 for t in threads:
150 t.join()
151
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000152 def pendingcalls_thread(self, context):
153 try:
154 self.pendingcalls_submit(context.l, context.n)
155 finally:
156 with context.lock:
157 context.nFinished += 1
158 nFinished = context.nFinished
159 if False and support.verbose:
160 print("finished threads: ", nFinished)
161 if nFinished == context.nThreads:
162 context.event.set()
163
Benjamin Petersona54c9092009-01-13 02:11:23 +0000164 def test_pendingcalls_non_threaded(self):
Ezio Melotti13925002011-03-16 11:05:33 +0200165 #again, just using the main thread, likely they will all be dispatched at
Benjamin Petersona54c9092009-01-13 02:11:23 +0000166 #once. It is ok to ask for too many, because we loop until we find a slot.
167 #the loop can be interrupted to dispatch.
168 #there are only 32 dispatch slots, so we go for twice that!
169 l = []
170 n = 64
171 self.pendingcalls_submit(l, n)
172 self.pendingcalls_wait(l, n)
173
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100174 def test_subinterps(self):
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100175 import builtins
176 r, w = os.pipe()
177 code = """if 1:
178 import sys, builtins, pickle
179 with open({:d}, "wb") as f:
180 pickle.dump(id(sys.modules), f)
181 pickle.dump(id(builtins), f)
182 """.format(w)
183 with open(r, "rb") as f:
184 ret = _testcapi.run_in_subinterp(code)
185 self.assertEqual(ret, 0)
186 self.assertNotEqual(pickle.load(f), id(sys.modules))
187 self.assertNotEqual(pickle.load(f), id(builtins))
188
Martin v. Löwisc15bdef2009-05-29 14:47:46 +0000189# Bug #6012
190class Test6012(unittest.TestCase):
191 def test(self):
192 self.assertEqual(_testcapi.argparsing("Hello", "World"), 1)
Benjamin Petersona54c9092009-01-13 02:11:23 +0000193
Antoine Pitrou8e605772011-04-25 21:21:07 +0200194
195class EmbeddingTest(unittest.TestCase):
196
Antoine Pitrou71cbafb2011-06-30 20:02:54 +0200197 @unittest.skipIf(
198 sys.platform.startswith('win'),
199 "test doesn't work under Windows")
Antoine Pitrou8e605772011-04-25 21:21:07 +0200200 def test_subinterps(self):
201 # XXX only tested under Unix checkouts
202 basepath = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
203 oldcwd = os.getcwd()
204 # This is needed otherwise we get a fatal error:
205 # "Py_Initialize: Unable to get the locale encoding
206 # LookupError: no codec search functions registered: can't find encoding"
207 os.chdir(basepath)
208 try:
209 exe = os.path.join(basepath, "Modules", "_testembed")
210 if not os.path.exists(exe):
211 self.skipTest("%r doesn't exist" % exe)
212 p = subprocess.Popen([exe],
213 stdout=subprocess.PIPE,
214 stderr=subprocess.PIPE)
215 (out, err) = p.communicate()
216 self.assertEqual(p.returncode, 0,
217 "bad returncode %d, stderr is %r" %
218 (p.returncode, err))
219 if support.verbose:
220 print()
221 print(out.decode('latin1'))
222 print(err.decode('latin1'))
223 finally:
224 os.chdir(oldcwd)
225
226
Ezio Melotti1ca87942013-02-23 06:42:19 +0200227@unittest.skipUnless(threading and _thread, 'Threading required for this test.')
Ezio Melotti29267c82013-02-23 05:52:46 +0200228class TestThreadState(unittest.TestCase):
229
230 @support.reap_threads
231 def test_thread_state(self):
232 # some extra thread-state tests driven via _testcapi
233 def target():
234 idents = []
235
236 def callback():
237 idents.append(_thread.get_ident())
238
239 _testcapi._test_thread_state(callback)
240 a = b = callback
241 time.sleep(1)
242 # Check our main thread is in the list exactly 3 times.
243 self.assertEqual(idents.count(_thread.get_ident()), 3,
244 "Couldn't find main thread correctly in the list")
245
246 target()
247 t = threading.Thread(target=target)
248 t.start()
249 t.join()
250
251
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000252def test_main():
Ezio Melotti29267c82013-02-23 05:52:46 +0200253 support.run_unittest(CAPITest, TestPendingCalls, Test6012,
254 EmbeddingTest, TestThreadState)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000255
256 for name in dir(_testcapi):
257 if name.startswith('test_'):
258 test = getattr(_testcapi, name)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000259 if support.verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000260 print("internal", name)
Collin Winter3add4d72007-08-29 23:37:32 +0000261 test()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000262
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000263if __name__ == "__main__":
264 test_main()