blob: 7a6870dc6af6026286626925be8c922fb9668d9f [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
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +00005import random
6import subprocess
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00007import sys
Benjamin Petersona54c9092009-01-13 02:11:23 +00008import time
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +00009import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +000010from test import support
Victor Stinner45df8202010-04-28 22:31:17 +000011try:
12 import threading
13except ImportError:
14 threading = None
Tim Petersd66595f2001-02-04 03:09:53 +000015import _testcapi
Tim Peters9ea17ac2001-02-02 05:57:15 +000016
Benjamin Petersona54c9092009-01-13 02:11:23 +000017
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000018def testfunction(self):
19 """some doc"""
20 return self
21
22class InstanceMethod:
23 id = _testcapi.instancemethod(id)
24 testfunction = _testcapi.instancemethod(testfunction)
25
26class CAPITest(unittest.TestCase):
27
28 def test_instancemethod(self):
29 inst = InstanceMethod()
30 self.assertEqual(id(inst), inst.id())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000031 self.assertTrue(inst.testfunction() is inst)
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000032 self.assertEqual(inst.testfunction.__doc__, testfunction.__doc__)
33 self.assertEqual(InstanceMethod.testfunction.__doc__, testfunction.__doc__)
34
35 InstanceMethod.testfunction.attribute = "test"
36 self.assertEqual(testfunction.attribute, "test")
37 self.assertRaises(AttributeError, setattr, inst.testfunction, "attribute", "test")
38
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000039 def test_no_FatalError_infinite_loop(self):
40 p = subprocess.Popen([sys.executable, "-c",
41 'import _testcapi;'
42 '_testcapi.crash_no_current_thread()'],
43 stdout=subprocess.PIPE,
44 stderr=subprocess.PIPE)
45 (out, err) = p.communicate()
46 self.assertEqual(out, b'')
47 # This used to cause an infinite loop.
48 self.assertEqual(err,
49 b'Fatal Python error:'
50 b' PyThreadState_Get: no current thread\n')
51
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000052
Victor Stinner45df8202010-04-28 22:31:17 +000053@unittest.skipUnless(threading, 'Threading required for this test.')
Benjamin Petersona54c9092009-01-13 02:11:23 +000054class TestPendingCalls(unittest.TestCase):
55
56 def pendingcalls_submit(self, l, n):
57 def callback():
58 #this function can be interrupted by thread switching so let's
59 #use an atomic operation
60 l.append(None)
61
62 for i in range(n):
63 time.sleep(random.random()*0.02) #0.01 secs on average
64 #try submitting callback until successful.
65 #rely on regular interrupt to flush queue if we are
66 #unsuccessful.
67 while True:
68 if _testcapi._pending_threadfunc(callback):
69 break;
70
Benjamin Petersone1cdfd72009-01-18 21:02:37 +000071 def pendingcalls_wait(self, l, n, context = None):
Benjamin Petersona54c9092009-01-13 02:11:23 +000072 #now, stick around until l[0] has grown to 10
73 count = 0;
74 while len(l) != n:
75 #this busy loop is where we expect to be interrupted to
76 #run our callbacks. Note that callbacks are only run on the
77 #main thread
Benjamin Petersone1cdfd72009-01-18 21:02:37 +000078 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +000079 print("(%i)"%(len(l),),)
80 for i in range(1000):
81 a = i*i
Benjamin Petersone1cdfd72009-01-18 21:02:37 +000082 if context and not context.event.is_set():
83 continue
Benjamin Petersona54c9092009-01-13 02:11:23 +000084 count += 1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000085 self.assertTrue(count < 10000,
Benjamin Petersona54c9092009-01-13 02:11:23 +000086 "timeout waiting for %i callbacks, got %i"%(n, len(l)))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +000087 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +000088 print("(%i)"%(len(l),))
89
90 def test_pendingcalls_threaded(self):
Benjamin Petersona54c9092009-01-13 02:11:23 +000091
92 #do every callback on a separate thread
Benjamin Petersone1cdfd72009-01-18 21:02:37 +000093 n = 32 #total callbacks
Benjamin Petersona54c9092009-01-13 02:11:23 +000094 threads = []
Benjamin Petersone1cdfd72009-01-18 21:02:37 +000095 class foo(object):pass
96 context = foo()
97 context.l = []
98 context.n = 2 #submits per thread
99 context.nThreads = n // context.n
100 context.nFinished = 0
101 context.lock = threading.Lock()
102 context.event = threading.Event()
103
104 for i in range(context.nThreads):
105 t = threading.Thread(target=self.pendingcalls_thread, args = (context,))
Benjamin Petersona54c9092009-01-13 02:11:23 +0000106 t.start()
107 threads.append(t)
108
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000109 self.pendingcalls_wait(context.l, n, context)
Benjamin Petersona54c9092009-01-13 02:11:23 +0000110
111 for t in threads:
112 t.join()
113
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000114 def pendingcalls_thread(self, context):
115 try:
116 self.pendingcalls_submit(context.l, context.n)
117 finally:
118 with context.lock:
119 context.nFinished += 1
120 nFinished = context.nFinished
121 if False and support.verbose:
122 print("finished threads: ", nFinished)
123 if nFinished == context.nThreads:
124 context.event.set()
125
Benjamin Petersona54c9092009-01-13 02:11:23 +0000126 def test_pendingcalls_non_threaded(self):
127 #again, just using the main thread, likely they will all be dispathced at
128 #once. It is ok to ask for too many, because we loop until we find a slot.
129 #the loop can be interrupted to dispatch.
130 #there are only 32 dispatch slots, so we go for twice that!
131 l = []
132 n = 64
133 self.pendingcalls_submit(l, n)
134 self.pendingcalls_wait(l, n)
135
Martin v. Löwisc15bdef2009-05-29 14:47:46 +0000136# Bug #6012
137class Test6012(unittest.TestCase):
138 def test(self):
139 self.assertEqual(_testcapi.argparsing("Hello", "World"), 1)
Benjamin Petersona54c9092009-01-13 02:11:23 +0000140
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000141def test_main():
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +0000142 support.run_unittest(CAPITest)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000143
144 for name in dir(_testcapi):
145 if name.startswith('test_'):
146 test = getattr(_testcapi, name)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000147 if support.verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000148 print("internal", name)
Collin Winter3add4d72007-08-29 23:37:32 +0000149 test()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000150
151 # some extra thread-state tests driven via _testcapi
152 def TestThreadState():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000153 if support.verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000154 print("auto-thread-state")
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000155
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000156 idents = []
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000157
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000158 def callback():
Georg Brandl2067bfd2008-05-25 13:05:15 +0000159 idents.append(_thread.get_ident())
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000160
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000161 _testcapi._test_thread_state(callback)
162 a = b = callback
163 time.sleep(1)
164 # Check our main thread is in the list exactly 3 times.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000165 if idents.count(_thread.get_ident()) != 3:
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000166 raise support.TestFailed(
Collin Winter3add4d72007-08-29 23:37:32 +0000167 "Couldn't find main thread correctly in the list")
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000168
Victor Stinner45df8202010-04-28 22:31:17 +0000169 if threading:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000170 import _thread
Christian Heimes5e696852008-04-09 08:37:03 +0000171 import time
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000172 TestThreadState()
Georg Brandl2067bfd2008-05-25 13:05:15 +0000173 t = threading.Thread(target=TestThreadState)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000174 t.start()
175 t.join()
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000176
Martin v. Löwisc15bdef2009-05-29 14:47:46 +0000177 support.run_unittest(TestPendingCalls, Test6012)
Benjamin Petersona54c9092009-01-13 02:11:23 +0000178
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +0000179
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000180if __name__ == "__main__":
181 test_main()