blob: c2c633ff5dd76947aa158f4dcf56340656f66b11 [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:
14 import threading
15except ImportError:
16 threading = None
Tim Petersd66595f2001-02-04 03:09:53 +000017import _testcapi
Tim Peters9ea17ac2001-02-02 05:57:15 +000018
Benjamin Petersona54c9092009-01-13 02:11:23 +000019
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000020def testfunction(self):
21 """some doc"""
22 return self
23
24class InstanceMethod:
25 id = _testcapi.instancemethod(id)
26 testfunction = _testcapi.instancemethod(testfunction)
27
28class CAPITest(unittest.TestCase):
29
30 def test_instancemethod(self):
31 inst = InstanceMethod()
32 self.assertEqual(id(inst), inst.id())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000033 self.assertTrue(inst.testfunction() is inst)
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000034 self.assertEqual(inst.testfunction.__doc__, testfunction.__doc__)
35 self.assertEqual(InstanceMethod.testfunction.__doc__, testfunction.__doc__)
36
37 InstanceMethod.testfunction.attribute = "test"
38 self.assertEqual(testfunction.attribute, "test")
39 self.assertRaises(AttributeError, setattr, inst.testfunction, "attribute", "test")
40
Stefan Krah0ca46242010-06-09 08:56:28 +000041 @unittest.skipUnless(threading, 'Threading required for this test.')
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000042 def test_no_FatalError_infinite_loop(self):
43 p = subprocess.Popen([sys.executable, "-c",
44 'import _testcapi;'
45 '_testcapi.crash_no_current_thread()'],
46 stdout=subprocess.PIPE,
47 stderr=subprocess.PIPE)
48 (out, err) = p.communicate()
49 self.assertEqual(out, b'')
50 # This used to cause an infinite loop.
Victor Stinner4000ffa2010-05-15 01:40:41 +000051 self.assertEqual(err.rstrip(),
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000052 b'Fatal Python error:'
Victor Stinner4000ffa2010-05-15 01:40:41 +000053 b' PyThreadState_Get: no current thread')
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000054
Antoine Pitrou915605c2011-02-24 20:53:48 +000055 def test_memoryview_from_NULL_pointer(self):
56 self.assertRaises(ValueError, _testcapi.make_memoryview_from_NULL_pointer)
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000057
Victor Stinner45df8202010-04-28 22:31:17 +000058@unittest.skipUnless(threading, 'Threading required for this test.')
Benjamin Petersona54c9092009-01-13 02:11:23 +000059class TestPendingCalls(unittest.TestCase):
60
61 def pendingcalls_submit(self, l, n):
62 def callback():
63 #this function can be interrupted by thread switching so let's
64 #use an atomic operation
65 l.append(None)
66
67 for i in range(n):
68 time.sleep(random.random()*0.02) #0.01 secs on average
69 #try submitting callback until successful.
70 #rely on regular interrupt to flush queue if we are
71 #unsuccessful.
72 while True:
73 if _testcapi._pending_threadfunc(callback):
74 break;
75
Benjamin Petersone1cdfd72009-01-18 21:02:37 +000076 def pendingcalls_wait(self, l, n, context = None):
Benjamin Petersona54c9092009-01-13 02:11:23 +000077 #now, stick around until l[0] has grown to 10
78 count = 0;
79 while len(l) != n:
80 #this busy loop is where we expect to be interrupted to
81 #run our callbacks. Note that callbacks are only run on the
82 #main thread
Benjamin Petersone1cdfd72009-01-18 21:02:37 +000083 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +000084 print("(%i)"%(len(l),),)
85 for i in range(1000):
86 a = i*i
Benjamin Petersone1cdfd72009-01-18 21:02:37 +000087 if context and not context.event.is_set():
88 continue
Benjamin Petersona54c9092009-01-13 02:11:23 +000089 count += 1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000090 self.assertTrue(count < 10000,
Benjamin Petersona54c9092009-01-13 02:11:23 +000091 "timeout waiting for %i callbacks, got %i"%(n, len(l)))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +000092 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +000093 print("(%i)"%(len(l),))
94
95 def test_pendingcalls_threaded(self):
Benjamin Petersona54c9092009-01-13 02:11:23 +000096
97 #do every callback on a separate thread
Benjamin Petersone1cdfd72009-01-18 21:02:37 +000098 n = 32 #total callbacks
Benjamin Petersona54c9092009-01-13 02:11:23 +000099 threads = []
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000100 class foo(object):pass
101 context = foo()
102 context.l = []
103 context.n = 2 #submits per thread
104 context.nThreads = n // context.n
105 context.nFinished = 0
106 context.lock = threading.Lock()
107 context.event = threading.Event()
108
109 for i in range(context.nThreads):
110 t = threading.Thread(target=self.pendingcalls_thread, args = (context,))
Benjamin Petersona54c9092009-01-13 02:11:23 +0000111 t.start()
112 threads.append(t)
113
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000114 self.pendingcalls_wait(context.l, n, context)
Benjamin Petersona54c9092009-01-13 02:11:23 +0000115
116 for t in threads:
117 t.join()
118
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000119 def pendingcalls_thread(self, context):
120 try:
121 self.pendingcalls_submit(context.l, context.n)
122 finally:
123 with context.lock:
124 context.nFinished += 1
125 nFinished = context.nFinished
126 if False and support.verbose:
127 print("finished threads: ", nFinished)
128 if nFinished == context.nThreads:
129 context.event.set()
130
Benjamin Petersona54c9092009-01-13 02:11:23 +0000131 def test_pendingcalls_non_threaded(self):
Ezio Melotti13925002011-03-16 11:05:33 +0200132 #again, just using the main thread, likely they will all be dispatched at
Benjamin Petersona54c9092009-01-13 02:11:23 +0000133 #once. It is ok to ask for too many, because we loop until we find a slot.
134 #the loop can be interrupted to dispatch.
135 #there are only 32 dispatch slots, so we go for twice that!
136 l = []
137 n = 64
138 self.pendingcalls_submit(l, n)
139 self.pendingcalls_wait(l, n)
140
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100141 def test_subinterps(self):
142 # XXX this test leaks in refleak runs
143 import builtins
144 r, w = os.pipe()
145 code = """if 1:
146 import sys, builtins, pickle
147 with open({:d}, "wb") as f:
148 pickle.dump(id(sys.modules), f)
149 pickle.dump(id(builtins), f)
150 """.format(w)
151 with open(r, "rb") as f:
152 ret = _testcapi.run_in_subinterp(code)
153 self.assertEqual(ret, 0)
154 self.assertNotEqual(pickle.load(f), id(sys.modules))
155 self.assertNotEqual(pickle.load(f), id(builtins))
156
Martin v. Löwisc15bdef2009-05-29 14:47:46 +0000157# Bug #6012
158class Test6012(unittest.TestCase):
159 def test(self):
160 self.assertEqual(_testcapi.argparsing("Hello", "World"), 1)
Benjamin Petersona54c9092009-01-13 02:11:23 +0000161
Antoine Pitrou8e605772011-04-25 21:21:07 +0200162
163class EmbeddingTest(unittest.TestCase):
164
Antoine Pitrou71cbafb2011-06-30 20:02:54 +0200165 @unittest.skipIf(
166 sys.platform.startswith('win'),
167 "test doesn't work under Windows")
Antoine Pitrou8e605772011-04-25 21:21:07 +0200168 def test_subinterps(self):
169 # XXX only tested under Unix checkouts
170 basepath = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
171 oldcwd = os.getcwd()
172 # This is needed otherwise we get a fatal error:
173 # "Py_Initialize: Unable to get the locale encoding
174 # LookupError: no codec search functions registered: can't find encoding"
175 os.chdir(basepath)
176 try:
177 exe = os.path.join(basepath, "Modules", "_testembed")
178 if not os.path.exists(exe):
179 self.skipTest("%r doesn't exist" % exe)
180 p = subprocess.Popen([exe],
181 stdout=subprocess.PIPE,
182 stderr=subprocess.PIPE)
183 (out, err) = p.communicate()
184 self.assertEqual(p.returncode, 0,
185 "bad returncode %d, stderr is %r" %
186 (p.returncode, err))
187 if support.verbose:
188 print()
189 print(out.decode('latin1'))
190 print(err.decode('latin1'))
191 finally:
192 os.chdir(oldcwd)
193
194
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000195def test_main():
Antoine Pitrou8e605772011-04-25 21:21:07 +0200196 support.run_unittest(CAPITest, TestPendingCalls, Test6012, EmbeddingTest)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000197
198 for name in dir(_testcapi):
199 if name.startswith('test_'):
200 test = getattr(_testcapi, name)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000201 if support.verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000202 print("internal", name)
Collin Winter3add4d72007-08-29 23:37:32 +0000203 test()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000204
205 # some extra thread-state tests driven via _testcapi
206 def TestThreadState():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000207 if support.verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000208 print("auto-thread-state")
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000209
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000210 idents = []
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000211
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000212 def callback():
Georg Brandl2067bfd2008-05-25 13:05:15 +0000213 idents.append(_thread.get_ident())
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000214
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000215 _testcapi._test_thread_state(callback)
216 a = b = callback
217 time.sleep(1)
218 # Check our main thread is in the list exactly 3 times.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000219 if idents.count(_thread.get_ident()) != 3:
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000220 raise support.TestFailed(
Collin Winter3add4d72007-08-29 23:37:32 +0000221 "Couldn't find main thread correctly in the list")
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000222
Victor Stinner45df8202010-04-28 22:31:17 +0000223 if threading:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000224 import _thread
Christian Heimes5e696852008-04-09 08:37:03 +0000225 import time
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000226 TestThreadState()
Georg Brandl2067bfd2008-05-25 13:05:15 +0000227 t = threading.Thread(target=TestThreadState)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000228 t.start()
229 t.join()
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000230
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +0000231
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000232if __name__ == "__main__":
233 test_main()