blob: ada393d9b469ee9d4a773196dad4627c6435986e [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
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
Victor Stinner45df8202010-04-28 22:31:17 +000012try:
13 import threading
14except ImportError:
15 threading = None
Tim Petersd66595f2001-02-04 03:09:53 +000016import _testcapi
Tim Peters9ea17ac2001-02-02 05:57:15 +000017
Benjamin Petersona54c9092009-01-13 02:11:23 +000018
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000019def testfunction(self):
20 """some doc"""
21 return self
22
23class InstanceMethod:
24 id = _testcapi.instancemethod(id)
25 testfunction = _testcapi.instancemethod(testfunction)
26
27class CAPITest(unittest.TestCase):
28
29 def test_instancemethod(self):
30 inst = InstanceMethod()
31 self.assertEqual(id(inst), inst.id())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000032 self.assertTrue(inst.testfunction() is inst)
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000033 self.assertEqual(inst.testfunction.__doc__, testfunction.__doc__)
34 self.assertEqual(InstanceMethod.testfunction.__doc__, testfunction.__doc__)
35
36 InstanceMethod.testfunction.attribute = "test"
37 self.assertEqual(testfunction.attribute, "test")
38 self.assertRaises(AttributeError, setattr, inst.testfunction, "attribute", "test")
39
Stefan Krah0ca46242010-06-09 08:56:28 +000040 @unittest.skipUnless(threading, 'Threading required for this test.')
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000041 def test_no_FatalError_infinite_loop(self):
42 p = subprocess.Popen([sys.executable, "-c",
43 'import _testcapi;'
44 '_testcapi.crash_no_current_thread()'],
45 stdout=subprocess.PIPE,
46 stderr=subprocess.PIPE)
47 (out, err) = p.communicate()
48 self.assertEqual(out, b'')
49 # This used to cause an infinite loop.
Victor Stinner4000ffa2010-05-15 01:40:41 +000050 self.assertEqual(err.rstrip(),
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000051 b'Fatal Python error:'
Victor Stinner4000ffa2010-05-15 01:40:41 +000052 b' PyThreadState_Get: no current thread')
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000053
Antoine Pitrou915605c2011-02-24 20:53:48 +000054 def test_memoryview_from_NULL_pointer(self):
55 self.assertRaises(ValueError, _testcapi.make_memoryview_from_NULL_pointer)
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000056
Victor Stinner45df8202010-04-28 22:31:17 +000057@unittest.skipUnless(threading, 'Threading required for this test.')
Benjamin Petersona54c9092009-01-13 02:11:23 +000058class TestPendingCalls(unittest.TestCase):
59
60 def pendingcalls_submit(self, l, n):
61 def callback():
62 #this function can be interrupted by thread switching so let's
63 #use an atomic operation
64 l.append(None)
65
66 for i in range(n):
67 time.sleep(random.random()*0.02) #0.01 secs on average
68 #try submitting callback until successful.
69 #rely on regular interrupt to flush queue if we are
70 #unsuccessful.
71 while True:
72 if _testcapi._pending_threadfunc(callback):
73 break;
74
Benjamin Petersone1cdfd72009-01-18 21:02:37 +000075 def pendingcalls_wait(self, l, n, context = None):
Benjamin Petersona54c9092009-01-13 02:11:23 +000076 #now, stick around until l[0] has grown to 10
77 count = 0;
78 while len(l) != n:
79 #this busy loop is where we expect to be interrupted to
80 #run our callbacks. Note that callbacks are only run on the
81 #main thread
Benjamin Petersone1cdfd72009-01-18 21:02:37 +000082 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +000083 print("(%i)"%(len(l),),)
84 for i in range(1000):
85 a = i*i
Benjamin Petersone1cdfd72009-01-18 21:02:37 +000086 if context and not context.event.is_set():
87 continue
Benjamin Petersona54c9092009-01-13 02:11:23 +000088 count += 1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000089 self.assertTrue(count < 10000,
Benjamin Petersona54c9092009-01-13 02:11:23 +000090 "timeout waiting for %i callbacks, got %i"%(n, len(l)))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +000091 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +000092 print("(%i)"%(len(l),))
93
94 def test_pendingcalls_threaded(self):
Benjamin Petersona54c9092009-01-13 02:11:23 +000095
96 #do every callback on a separate thread
Benjamin Petersone1cdfd72009-01-18 21:02:37 +000097 n = 32 #total callbacks
Benjamin Petersona54c9092009-01-13 02:11:23 +000098 threads = []
Benjamin Petersone1cdfd72009-01-18 21:02:37 +000099 class foo(object):pass
100 context = foo()
101 context.l = []
102 context.n = 2 #submits per thread
103 context.nThreads = n // context.n
104 context.nFinished = 0
105 context.lock = threading.Lock()
106 context.event = threading.Event()
107
108 for i in range(context.nThreads):
109 t = threading.Thread(target=self.pendingcalls_thread, args = (context,))
Benjamin Petersona54c9092009-01-13 02:11:23 +0000110 t.start()
111 threads.append(t)
112
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000113 self.pendingcalls_wait(context.l, n, context)
Benjamin Petersona54c9092009-01-13 02:11:23 +0000114
115 for t in threads:
116 t.join()
117
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000118 def pendingcalls_thread(self, context):
119 try:
120 self.pendingcalls_submit(context.l, context.n)
121 finally:
122 with context.lock:
123 context.nFinished += 1
124 nFinished = context.nFinished
125 if False and support.verbose:
126 print("finished threads: ", nFinished)
127 if nFinished == context.nThreads:
128 context.event.set()
129
Benjamin Petersona54c9092009-01-13 02:11:23 +0000130 def test_pendingcalls_non_threaded(self):
Ezio Melotti13925002011-03-16 11:05:33 +0200131 #again, just using the main thread, likely they will all be dispatched at
Benjamin Petersona54c9092009-01-13 02:11:23 +0000132 #once. It is ok to ask for too many, because we loop until we find a slot.
133 #the loop can be interrupted to dispatch.
134 #there are only 32 dispatch slots, so we go for twice that!
135 l = []
136 n = 64
137 self.pendingcalls_submit(l, n)
138 self.pendingcalls_wait(l, n)
139
Martin v. Löwisc15bdef2009-05-29 14:47:46 +0000140# Bug #6012
141class Test6012(unittest.TestCase):
142 def test(self):
143 self.assertEqual(_testcapi.argparsing("Hello", "World"), 1)
Benjamin Petersona54c9092009-01-13 02:11:23 +0000144
Antoine Pitrou8e605772011-04-25 21:21:07 +0200145
146class EmbeddingTest(unittest.TestCase):
147
Antoine Pitrou71cbafb2011-06-30 20:02:54 +0200148 @unittest.skipIf(
149 sys.platform.startswith('win'),
150 "test doesn't work under Windows")
Antoine Pitrou8e605772011-04-25 21:21:07 +0200151 def test_subinterps(self):
152 # XXX only tested under Unix checkouts
153 basepath = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
154 oldcwd = os.getcwd()
155 # This is needed otherwise we get a fatal error:
156 # "Py_Initialize: Unable to get the locale encoding
157 # LookupError: no codec search functions registered: can't find encoding"
158 os.chdir(basepath)
159 try:
160 exe = os.path.join(basepath, "Modules", "_testembed")
161 if not os.path.exists(exe):
162 self.skipTest("%r doesn't exist" % exe)
163 p = subprocess.Popen([exe],
164 stdout=subprocess.PIPE,
165 stderr=subprocess.PIPE)
166 (out, err) = p.communicate()
167 self.assertEqual(p.returncode, 0,
168 "bad returncode %d, stderr is %r" %
169 (p.returncode, err))
170 if support.verbose:
171 print()
172 print(out.decode('latin1'))
173 print(err.decode('latin1'))
174 finally:
175 os.chdir(oldcwd)
176
177
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000178def test_main():
Antoine Pitrou8e605772011-04-25 21:21:07 +0200179 support.run_unittest(CAPITest, TestPendingCalls, Test6012, EmbeddingTest)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000180
181 for name in dir(_testcapi):
182 if name.startswith('test_'):
183 test = getattr(_testcapi, name)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000184 if support.verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000185 print("internal", name)
Collin Winter3add4d72007-08-29 23:37:32 +0000186 test()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000187
188 # some extra thread-state tests driven via _testcapi
189 def TestThreadState():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000190 if support.verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000191 print("auto-thread-state")
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000192
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000193 idents = []
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000194
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000195 def callback():
Georg Brandl2067bfd2008-05-25 13:05:15 +0000196 idents.append(_thread.get_ident())
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000197
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000198 _testcapi._test_thread_state(callback)
199 a = b = callback
200 time.sleep(1)
201 # Check our main thread is in the list exactly 3 times.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000202 if idents.count(_thread.get_ident()) != 3:
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000203 raise support.TestFailed(
Collin Winter3add4d72007-08-29 23:37:32 +0000204 "Couldn't find main thread correctly in the list")
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000205
Victor Stinner45df8202010-04-28 22:31:17 +0000206 if threading:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000207 import _thread
Christian Heimes5e696852008-04-09 08:37:03 +0000208 import time
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000209 TestThreadState()
Georg Brandl2067bfd2008-05-25 13:05:15 +0000210 t = threading.Thread(target=TestThreadState)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000211 t.start()
212 t.join()
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000213
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +0000214
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000215if __name__ == "__main__":
216 test_main()