blob: 1c4c0f8c46e2e3cd247c18d919d4944002579932 [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):
Ezio Melotti1f386212013-03-07 18:44:29 +020049 with support.suppress_crash_popup():
50 p = subprocess.Popen([sys.executable, "-c",
51 'import _testcapi;'
52 '_testcapi.crash_no_current_thread()'],
53 stdout=subprocess.PIPE,
54 stderr=subprocess.PIPE)
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000055 (out, err) = p.communicate()
56 self.assertEqual(out, b'')
57 # This used to cause an infinite loop.
Victor Stinner4000ffa2010-05-15 01:40:41 +000058 self.assertEqual(err.rstrip(),
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000059 b'Fatal Python error:'
Victor Stinner4000ffa2010-05-15 01:40:41 +000060 b' PyThreadState_Get: no current thread')
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000061
Antoine Pitrou915605c2011-02-24 20:53:48 +000062 def test_memoryview_from_NULL_pointer(self):
63 self.assertRaises(ValueError, _testcapi.make_memoryview_from_NULL_pointer)
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000064
Stefan Krahfd24f9e2012-08-20 11:04:24 +020065 @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
66 def test_seq_bytes_to_charp_array(self):
67 # Issue #15732: crash in _PySequence_BytesToCharpArray()
68 class Z(object):
69 def __len__(self):
70 return 1
71 self.assertRaises(TypeError, _posixsubprocess.fork_exec,
72 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 +020073 # Issue #15736: overflow in _PySequence_BytesToCharpArray()
74 class Z(object):
75 def __len__(self):
76 return sys.maxsize
77 def __getitem__(self, i):
78 return b'x'
79 self.assertRaises(MemoryError, _posixsubprocess.fork_exec,
80 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 +020081
Stefan Krahdb579d72012-08-20 14:36:47 +020082 @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
83 def test_subprocess_fork_exec(self):
84 class Z(object):
85 def __len__(self):
86 return 1
87
88 # Issue #15738: crash in subprocess_fork_exec()
89 self.assertRaises(TypeError, _posixsubprocess.fork_exec,
90 Z(),[b'1'],3,[1, 2],5,6,7,8,9,10,11,12,13,14,15,16,17)
91
Victor Stinner45df8202010-04-28 22:31:17 +000092@unittest.skipUnless(threading, 'Threading required for this test.')
Benjamin Petersona54c9092009-01-13 02:11:23 +000093class TestPendingCalls(unittest.TestCase):
94
95 def pendingcalls_submit(self, l, n):
96 def callback():
97 #this function can be interrupted by thread switching so let's
98 #use an atomic operation
99 l.append(None)
100
101 for i in range(n):
102 time.sleep(random.random()*0.02) #0.01 secs on average
103 #try submitting callback until successful.
104 #rely on regular interrupt to flush queue if we are
105 #unsuccessful.
106 while True:
107 if _testcapi._pending_threadfunc(callback):
108 break;
109
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000110 def pendingcalls_wait(self, l, n, context = None):
Benjamin Petersona54c9092009-01-13 02:11:23 +0000111 #now, stick around until l[0] has grown to 10
112 count = 0;
113 while len(l) != n:
114 #this busy loop is where we expect to be interrupted to
115 #run our callbacks. Note that callbacks are only run on the
116 #main thread
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000117 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +0000118 print("(%i)"%(len(l),),)
119 for i in range(1000):
120 a = i*i
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000121 if context and not context.event.is_set():
122 continue
Benjamin Petersona54c9092009-01-13 02:11:23 +0000123 count += 1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000124 self.assertTrue(count < 10000,
Benjamin Petersona54c9092009-01-13 02:11:23 +0000125 "timeout waiting for %i callbacks, got %i"%(n, len(l)))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000126 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +0000127 print("(%i)"%(len(l),))
128
129 def test_pendingcalls_threaded(self):
Benjamin Petersona54c9092009-01-13 02:11:23 +0000130
131 #do every callback on a separate thread
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000132 n = 32 #total callbacks
Benjamin Petersona54c9092009-01-13 02:11:23 +0000133 threads = []
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000134 class foo(object):pass
135 context = foo()
136 context.l = []
137 context.n = 2 #submits per thread
138 context.nThreads = n // context.n
139 context.nFinished = 0
140 context.lock = threading.Lock()
141 context.event = threading.Event()
142
143 for i in range(context.nThreads):
144 t = threading.Thread(target=self.pendingcalls_thread, args = (context,))
Benjamin Petersona54c9092009-01-13 02:11:23 +0000145 t.start()
146 threads.append(t)
147
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000148 self.pendingcalls_wait(context.l, n, context)
Benjamin Petersona54c9092009-01-13 02:11:23 +0000149
150 for t in threads:
151 t.join()
152
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000153 def pendingcalls_thread(self, context):
154 try:
155 self.pendingcalls_submit(context.l, context.n)
156 finally:
157 with context.lock:
158 context.nFinished += 1
159 nFinished = context.nFinished
160 if False and support.verbose:
161 print("finished threads: ", nFinished)
162 if nFinished == context.nThreads:
163 context.event.set()
164
Benjamin Petersona54c9092009-01-13 02:11:23 +0000165 def test_pendingcalls_non_threaded(self):
Ezio Melotti13925002011-03-16 11:05:33 +0200166 #again, just using the main thread, likely they will all be dispatched at
Benjamin Petersona54c9092009-01-13 02:11:23 +0000167 #once. It is ok to ask for too many, because we loop until we find a slot.
168 #the loop can be interrupted to dispatch.
169 #there are only 32 dispatch slots, so we go for twice that!
170 l = []
171 n = 64
172 self.pendingcalls_submit(l, n)
173 self.pendingcalls_wait(l, n)
174
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100175 def test_subinterps(self):
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100176 import builtins
177 r, w = os.pipe()
178 code = """if 1:
179 import sys, builtins, pickle
180 with open({:d}, "wb") as f:
181 pickle.dump(id(sys.modules), f)
182 pickle.dump(id(builtins), f)
183 """.format(w)
184 with open(r, "rb") as f:
185 ret = _testcapi.run_in_subinterp(code)
186 self.assertEqual(ret, 0)
187 self.assertNotEqual(pickle.load(f), id(sys.modules))
188 self.assertNotEqual(pickle.load(f), id(builtins))
189
Martin v. Löwisc15bdef2009-05-29 14:47:46 +0000190# Bug #6012
191class Test6012(unittest.TestCase):
192 def test(self):
193 self.assertEqual(_testcapi.argparsing("Hello", "World"), 1)
Benjamin Petersona54c9092009-01-13 02:11:23 +0000194
Antoine Pitrou8e605772011-04-25 21:21:07 +0200195
196class EmbeddingTest(unittest.TestCase):
197
Antoine Pitrou71cbafb2011-06-30 20:02:54 +0200198 @unittest.skipIf(
199 sys.platform.startswith('win'),
200 "test doesn't work under Windows")
Antoine Pitrou8e605772011-04-25 21:21:07 +0200201 def test_subinterps(self):
202 # XXX only tested under Unix checkouts
203 basepath = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
204 oldcwd = os.getcwd()
205 # This is needed otherwise we get a fatal error:
206 # "Py_Initialize: Unable to get the locale encoding
207 # LookupError: no codec search functions registered: can't find encoding"
208 os.chdir(basepath)
209 try:
210 exe = os.path.join(basepath, "Modules", "_testembed")
211 if not os.path.exists(exe):
212 self.skipTest("%r doesn't exist" % exe)
213 p = subprocess.Popen([exe],
214 stdout=subprocess.PIPE,
215 stderr=subprocess.PIPE)
216 (out, err) = p.communicate()
217 self.assertEqual(p.returncode, 0,
218 "bad returncode %d, stderr is %r" %
219 (p.returncode, err))
220 if support.verbose:
221 print()
222 print(out.decode('latin1'))
223 print(err.decode('latin1'))
224 finally:
225 os.chdir(oldcwd)
226
227
Ezio Melotti1ca87942013-02-23 06:42:19 +0200228@unittest.skipUnless(threading and _thread, 'Threading required for this test.')
Ezio Melotti29267c82013-02-23 05:52:46 +0200229class TestThreadState(unittest.TestCase):
230
231 @support.reap_threads
232 def test_thread_state(self):
233 # some extra thread-state tests driven via _testcapi
234 def target():
235 idents = []
236
237 def callback():
238 idents.append(_thread.get_ident())
239
240 _testcapi._test_thread_state(callback)
241 a = b = callback
242 time.sleep(1)
243 # Check our main thread is in the list exactly 3 times.
244 self.assertEqual(idents.count(_thread.get_ident()), 3,
245 "Couldn't find main thread correctly in the list")
246
247 target()
248 t = threading.Thread(target=target)
249 t.start()
250 t.join()
251
252
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000253def test_main():
Ezio Melotti29267c82013-02-23 05:52:46 +0200254 support.run_unittest(CAPITest, TestPendingCalls, Test6012,
255 EmbeddingTest, TestThreadState)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000256
257 for name in dir(_testcapi):
258 if name.startswith('test_'):
259 test = getattr(_testcapi, name)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000260 if support.verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000261 print("internal", name)
Collin Winter3add4d72007-08-29 23:37:32 +0000262 test()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000263
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000264if __name__ == "__main__":
265 test_main()