blob: 32f8fae25af441f44f215d58eb921b6f4ce866b8 [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
Stefan Krah0ca46242010-06-09 08:56:28 +000039 @unittest.skipUnless(threading, 'Threading required for this test.')
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000040 def test_no_FatalError_infinite_loop(self):
41 p = subprocess.Popen([sys.executable, "-c",
42 'import _testcapi;'
43 '_testcapi.crash_no_current_thread()'],
44 stdout=subprocess.PIPE,
45 stderr=subprocess.PIPE)
46 (out, err) = p.communicate()
47 self.assertEqual(out, b'')
48 # This used to cause an infinite loop.
Victor Stinner4000ffa2010-05-15 01:40:41 +000049 self.assertEqual(err.rstrip(),
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000050 b'Fatal Python error:'
Victor Stinner4000ffa2010-05-15 01:40:41 +000051 b' PyThreadState_Get: no current thread')
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000052
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000053
Victor Stinner45df8202010-04-28 22:31:17 +000054@unittest.skipUnless(threading, 'Threading required for this test.')
Benjamin Petersona54c9092009-01-13 02:11:23 +000055class TestPendingCalls(unittest.TestCase):
56
57 def pendingcalls_submit(self, l, n):
58 def callback():
59 #this function can be interrupted by thread switching so let's
60 #use an atomic operation
61 l.append(None)
62
63 for i in range(n):
64 time.sleep(random.random()*0.02) #0.01 secs on average
65 #try submitting callback until successful.
66 #rely on regular interrupt to flush queue if we are
67 #unsuccessful.
68 while True:
69 if _testcapi._pending_threadfunc(callback):
70 break;
71
Benjamin Petersone1cdfd72009-01-18 21:02:37 +000072 def pendingcalls_wait(self, l, n, context = None):
Benjamin Petersona54c9092009-01-13 02:11:23 +000073 #now, stick around until l[0] has grown to 10
74 count = 0;
75 while len(l) != n:
76 #this busy loop is where we expect to be interrupted to
77 #run our callbacks. Note that callbacks are only run on the
78 #main thread
Benjamin Petersone1cdfd72009-01-18 21:02:37 +000079 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +000080 print("(%i)"%(len(l),),)
81 for i in range(1000):
82 a = i*i
Benjamin Petersone1cdfd72009-01-18 21:02:37 +000083 if context and not context.event.is_set():
84 continue
Benjamin Petersona54c9092009-01-13 02:11:23 +000085 count += 1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000086 self.assertTrue(count < 10000,
Benjamin Petersona54c9092009-01-13 02:11:23 +000087 "timeout waiting for %i callbacks, got %i"%(n, len(l)))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +000088 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +000089 print("(%i)"%(len(l),))
90
91 def test_pendingcalls_threaded(self):
Benjamin Petersona54c9092009-01-13 02:11:23 +000092
93 #do every callback on a separate thread
Benjamin Petersone1cdfd72009-01-18 21:02:37 +000094 n = 32 #total callbacks
Benjamin Petersona54c9092009-01-13 02:11:23 +000095 threads = []
Benjamin Petersone1cdfd72009-01-18 21:02:37 +000096 class foo(object):pass
97 context = foo()
98 context.l = []
99 context.n = 2 #submits per thread
100 context.nThreads = n // context.n
101 context.nFinished = 0
102 context.lock = threading.Lock()
103 context.event = threading.Event()
104
105 for i in range(context.nThreads):
106 t = threading.Thread(target=self.pendingcalls_thread, args = (context,))
Benjamin Petersona54c9092009-01-13 02:11:23 +0000107 t.start()
108 threads.append(t)
109
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000110 self.pendingcalls_wait(context.l, n, context)
Benjamin Petersona54c9092009-01-13 02:11:23 +0000111
112 for t in threads:
113 t.join()
114
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000115 def pendingcalls_thread(self, context):
116 try:
117 self.pendingcalls_submit(context.l, context.n)
118 finally:
119 with context.lock:
120 context.nFinished += 1
121 nFinished = context.nFinished
122 if False and support.verbose:
123 print("finished threads: ", nFinished)
124 if nFinished == context.nThreads:
125 context.event.set()
126
Benjamin Petersona54c9092009-01-13 02:11:23 +0000127 def test_pendingcalls_non_threaded(self):
128 #again, just using the main thread, likely they will all be dispathced at
129 #once. It is ok to ask for too many, because we loop until we find a slot.
130 #the loop can be interrupted to dispatch.
131 #there are only 32 dispatch slots, so we go for twice that!
132 l = []
133 n = 64
134 self.pendingcalls_submit(l, n)
135 self.pendingcalls_wait(l, n)
136
Martin v. Löwisc15bdef2009-05-29 14:47:46 +0000137# Bug #6012
138class Test6012(unittest.TestCase):
139 def test(self):
140 self.assertEqual(_testcapi.argparsing("Hello", "World"), 1)
Benjamin Petersona54c9092009-01-13 02:11:23 +0000141
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000142def test_main():
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +0000143 support.run_unittest(CAPITest)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000144
145 for name in dir(_testcapi):
146 if name.startswith('test_'):
147 test = getattr(_testcapi, name)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000148 if support.verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000149 print("internal", name)
Collin Winter3add4d72007-08-29 23:37:32 +0000150 test()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000151
152 # some extra thread-state tests driven via _testcapi
153 def TestThreadState():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000154 if support.verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000155 print("auto-thread-state")
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000156
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000157 idents = []
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000158
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000159 def callback():
Georg Brandl2067bfd2008-05-25 13:05:15 +0000160 idents.append(_thread.get_ident())
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000161
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000162 _testcapi._test_thread_state(callback)
163 a = b = callback
164 time.sleep(1)
165 # Check our main thread is in the list exactly 3 times.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000166 if idents.count(_thread.get_ident()) != 3:
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000167 raise support.TestFailed(
Collin Winter3add4d72007-08-29 23:37:32 +0000168 "Couldn't find main thread correctly in the list")
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000169
Victor Stinner45df8202010-04-28 22:31:17 +0000170 if threading:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000171 import _thread
Christian Heimes5e696852008-04-09 08:37:03 +0000172 import time
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000173 TestThreadState()
Georg Brandl2067bfd2008-05-25 13:05:15 +0000174 t = threading.Thread(target=TestThreadState)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000175 t.start()
176 t.join()
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000177
Martin v. Löwisc15bdef2009-05-29 14:47:46 +0000178 support.run_unittest(TestPendingCalls, Test6012)
Benjamin Petersona54c9092009-01-13 02:11:23 +0000179
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +0000180
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000181if __name__ == "__main__":
182 test_main()