blob: d61bf363dc3126d3e2ca643f1400002c9afee7a1 [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
Ezio Melotti29267c82013-02-23 05:52:46 +020011import _thread
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000012import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +000013from test import support
Victor Stinner45df8202010-04-28 22:31:17 +000014try:
Stefan Krahfd24f9e2012-08-20 11:04:24 +020015 import _posixsubprocess
16except ImportError:
17 _posixsubprocess = None
18try:
Victor Stinner45df8202010-04-28 22:31:17 +000019 import threading
20except ImportError:
21 threading = None
Tim Petersd66595f2001-02-04 03:09:53 +000022import _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):
48 p = subprocess.Popen([sys.executable, "-c",
49 'import _testcapi;'
50 '_testcapi.crash_no_current_thread()'],
51 stdout=subprocess.PIPE,
52 stderr=subprocess.PIPE)
53 (out, err) = p.communicate()
54 self.assertEqual(out, b'')
55 # This used to cause an infinite loop.
Victor Stinner4000ffa2010-05-15 01:40:41 +000056 self.assertEqual(err.rstrip(),
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000057 b'Fatal Python error:'
Victor Stinner4000ffa2010-05-15 01:40:41 +000058 b' PyThreadState_Get: no current thread')
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000059
Antoine Pitrou915605c2011-02-24 20:53:48 +000060 def test_memoryview_from_NULL_pointer(self):
61 self.assertRaises(ValueError, _testcapi.make_memoryview_from_NULL_pointer)
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000062
Stefan Krahfd24f9e2012-08-20 11:04:24 +020063 @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
64 def test_seq_bytes_to_charp_array(self):
65 # Issue #15732: crash in _PySequence_BytesToCharpArray()
66 class Z(object):
67 def __len__(self):
68 return 1
69 self.assertRaises(TypeError, _posixsubprocess.fork_exec,
70 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 +020071 # Issue #15736: overflow in _PySequence_BytesToCharpArray()
72 class Z(object):
73 def __len__(self):
74 return sys.maxsize
75 def __getitem__(self, i):
76 return b'x'
77 self.assertRaises(MemoryError, _posixsubprocess.fork_exec,
78 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 +020079
Stefan Krahdb579d72012-08-20 14:36:47 +020080 @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
81 def test_subprocess_fork_exec(self):
82 class Z(object):
83 def __len__(self):
84 return 1
85
86 # Issue #15738: crash in subprocess_fork_exec()
87 self.assertRaises(TypeError, _posixsubprocess.fork_exec,
88 Z(),[b'1'],3,[1, 2],5,6,7,8,9,10,11,12,13,14,15,16,17)
89
Victor Stinner45df8202010-04-28 22:31:17 +000090@unittest.skipUnless(threading, 'Threading required for this test.')
Benjamin Petersona54c9092009-01-13 02:11:23 +000091class TestPendingCalls(unittest.TestCase):
92
93 def pendingcalls_submit(self, l, n):
94 def callback():
95 #this function can be interrupted by thread switching so let's
96 #use an atomic operation
97 l.append(None)
98
99 for i in range(n):
100 time.sleep(random.random()*0.02) #0.01 secs on average
101 #try submitting callback until successful.
102 #rely on regular interrupt to flush queue if we are
103 #unsuccessful.
104 while True:
105 if _testcapi._pending_threadfunc(callback):
106 break;
107
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000108 def pendingcalls_wait(self, l, n, context = None):
Benjamin Petersona54c9092009-01-13 02:11:23 +0000109 #now, stick around until l[0] has grown to 10
110 count = 0;
111 while len(l) != n:
112 #this busy loop is where we expect to be interrupted to
113 #run our callbacks. Note that callbacks are only run on the
114 #main thread
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000115 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +0000116 print("(%i)"%(len(l),),)
117 for i in range(1000):
118 a = i*i
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000119 if context and not context.event.is_set():
120 continue
Benjamin Petersona54c9092009-01-13 02:11:23 +0000121 count += 1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000122 self.assertTrue(count < 10000,
Benjamin Petersona54c9092009-01-13 02:11:23 +0000123 "timeout waiting for %i callbacks, got %i"%(n, len(l)))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000124 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +0000125 print("(%i)"%(len(l),))
126
127 def test_pendingcalls_threaded(self):
Benjamin Petersona54c9092009-01-13 02:11:23 +0000128
129 #do every callback on a separate thread
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000130 n = 32 #total callbacks
Benjamin Petersona54c9092009-01-13 02:11:23 +0000131 threads = []
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000132 class foo(object):pass
133 context = foo()
134 context.l = []
135 context.n = 2 #submits per thread
136 context.nThreads = n // context.n
137 context.nFinished = 0
138 context.lock = threading.Lock()
139 context.event = threading.Event()
140
141 for i in range(context.nThreads):
142 t = threading.Thread(target=self.pendingcalls_thread, args = (context,))
Benjamin Petersona54c9092009-01-13 02:11:23 +0000143 t.start()
144 threads.append(t)
145
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000146 self.pendingcalls_wait(context.l, n, context)
Benjamin Petersona54c9092009-01-13 02:11:23 +0000147
148 for t in threads:
149 t.join()
150
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000151 def pendingcalls_thread(self, context):
152 try:
153 self.pendingcalls_submit(context.l, context.n)
154 finally:
155 with context.lock:
156 context.nFinished += 1
157 nFinished = context.nFinished
158 if False and support.verbose:
159 print("finished threads: ", nFinished)
160 if nFinished == context.nThreads:
161 context.event.set()
162
Benjamin Petersona54c9092009-01-13 02:11:23 +0000163 def test_pendingcalls_non_threaded(self):
Ezio Melotti13925002011-03-16 11:05:33 +0200164 #again, just using the main thread, likely they will all be dispatched at
Benjamin Petersona54c9092009-01-13 02:11:23 +0000165 #once. It is ok to ask for too many, because we loop until we find a slot.
166 #the loop can be interrupted to dispatch.
167 #there are only 32 dispatch slots, so we go for twice that!
168 l = []
169 n = 64
170 self.pendingcalls_submit(l, n)
171 self.pendingcalls_wait(l, n)
172
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100173 def test_subinterps(self):
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100174 import builtins
175 r, w = os.pipe()
176 code = """if 1:
177 import sys, builtins, pickle
178 with open({:d}, "wb") as f:
179 pickle.dump(id(sys.modules), f)
180 pickle.dump(id(builtins), f)
181 """.format(w)
182 with open(r, "rb") as f:
183 ret = _testcapi.run_in_subinterp(code)
184 self.assertEqual(ret, 0)
185 self.assertNotEqual(pickle.load(f), id(sys.modules))
186 self.assertNotEqual(pickle.load(f), id(builtins))
187
Martin v. Löwisc15bdef2009-05-29 14:47:46 +0000188# Bug #6012
189class Test6012(unittest.TestCase):
190 def test(self):
191 self.assertEqual(_testcapi.argparsing("Hello", "World"), 1)
Benjamin Petersona54c9092009-01-13 02:11:23 +0000192
Antoine Pitrou8e605772011-04-25 21:21:07 +0200193
194class EmbeddingTest(unittest.TestCase):
195
Antoine Pitrou71cbafb2011-06-30 20:02:54 +0200196 @unittest.skipIf(
197 sys.platform.startswith('win'),
198 "test doesn't work under Windows")
Antoine Pitrou8e605772011-04-25 21:21:07 +0200199 def test_subinterps(self):
200 # XXX only tested under Unix checkouts
201 basepath = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
202 oldcwd = os.getcwd()
203 # This is needed otherwise we get a fatal error:
204 # "Py_Initialize: Unable to get the locale encoding
205 # LookupError: no codec search functions registered: can't find encoding"
206 os.chdir(basepath)
207 try:
208 exe = os.path.join(basepath, "Modules", "_testembed")
209 if not os.path.exists(exe):
210 self.skipTest("%r doesn't exist" % exe)
211 p = subprocess.Popen([exe],
212 stdout=subprocess.PIPE,
213 stderr=subprocess.PIPE)
214 (out, err) = p.communicate()
215 self.assertEqual(p.returncode, 0,
216 "bad returncode %d, stderr is %r" %
217 (p.returncode, err))
218 if support.verbose:
219 print()
220 print(out.decode('latin1'))
221 print(err.decode('latin1'))
222 finally:
223 os.chdir(oldcwd)
224
225
Ezio Melotti29267c82013-02-23 05:52:46 +0200226@unittest.skipUnless(threading, 'Threading required for this test.')
227class TestThreadState(unittest.TestCase):
228
229 @support.reap_threads
230 def test_thread_state(self):
231 # some extra thread-state tests driven via _testcapi
232 def target():
233 idents = []
234
235 def callback():
236 idents.append(_thread.get_ident())
237
238 _testcapi._test_thread_state(callback)
239 a = b = callback
240 time.sleep(1)
241 # Check our main thread is in the list exactly 3 times.
242 self.assertEqual(idents.count(_thread.get_ident()), 3,
243 "Couldn't find main thread correctly in the list")
244
245 target()
246 t = threading.Thread(target=target)
247 t.start()
248 t.join()
249
250
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000251def test_main():
Ezio Melotti29267c82013-02-23 05:52:46 +0200252 support.run_unittest(CAPITest, TestPendingCalls, Test6012,
253 EmbeddingTest, TestThreadState)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000254
255 for name in dir(_testcapi):
256 if name.startswith('test_'):
257 test = getattr(_testcapi, name)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000258 if support.verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000259 print("internal", name)
Collin Winter3add4d72007-08-29 23:37:32 +0000260 test()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000261
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000262if __name__ == "__main__":
263 test_main()