blob: 529a2a5e1630595c3a4ab213c977ac48d4d3f30e [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
Antoine Pitrou915605c2011-02-24 20:53:48 +000053 def test_memoryview_from_NULL_pointer(self):
54 self.assertRaises(ValueError, _testcapi.make_memoryview_from_NULL_pointer)
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000055
Victor Stinner45df8202010-04-28 22:31:17 +000056@unittest.skipUnless(threading, 'Threading required for this test.')
Benjamin Petersona54c9092009-01-13 02:11:23 +000057class TestPendingCalls(unittest.TestCase):
58
59 def pendingcalls_submit(self, l, n):
60 def callback():
61 #this function can be interrupted by thread switching so let's
62 #use an atomic operation
63 l.append(None)
64
65 for i in range(n):
66 time.sleep(random.random()*0.02) #0.01 secs on average
67 #try submitting callback until successful.
68 #rely on regular interrupt to flush queue if we are
69 #unsuccessful.
70 while True:
71 if _testcapi._pending_threadfunc(callback):
72 break;
73
Benjamin Petersone1cdfd72009-01-18 21:02:37 +000074 def pendingcalls_wait(self, l, n, context = None):
Benjamin Petersona54c9092009-01-13 02:11:23 +000075 #now, stick around until l[0] has grown to 10
76 count = 0;
77 while len(l) != n:
78 #this busy loop is where we expect to be interrupted to
79 #run our callbacks. Note that callbacks are only run on the
80 #main thread
Benjamin Petersone1cdfd72009-01-18 21:02:37 +000081 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +000082 print("(%i)"%(len(l),),)
83 for i in range(1000):
84 a = i*i
Benjamin Petersone1cdfd72009-01-18 21:02:37 +000085 if context and not context.event.is_set():
86 continue
Benjamin Petersona54c9092009-01-13 02:11:23 +000087 count += 1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000088 self.assertTrue(count < 10000,
Benjamin Petersona54c9092009-01-13 02:11:23 +000089 "timeout waiting for %i callbacks, got %i"%(n, len(l)))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +000090 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +000091 print("(%i)"%(len(l),))
92
93 def test_pendingcalls_threaded(self):
Benjamin Petersona54c9092009-01-13 02:11:23 +000094
95 #do every callback on a separate thread
Benjamin Petersone1cdfd72009-01-18 21:02:37 +000096 n = 32 #total callbacks
Benjamin Petersona54c9092009-01-13 02:11:23 +000097 threads = []
Benjamin Petersone1cdfd72009-01-18 21:02:37 +000098 class foo(object):pass
99 context = foo()
100 context.l = []
101 context.n = 2 #submits per thread
102 context.nThreads = n // context.n
103 context.nFinished = 0
104 context.lock = threading.Lock()
105 context.event = threading.Event()
106
107 for i in range(context.nThreads):
108 t = threading.Thread(target=self.pendingcalls_thread, args = (context,))
Benjamin Petersona54c9092009-01-13 02:11:23 +0000109 t.start()
110 threads.append(t)
111
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000112 self.pendingcalls_wait(context.l, n, context)
Benjamin Petersona54c9092009-01-13 02:11:23 +0000113
114 for t in threads:
115 t.join()
116
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000117 def pendingcalls_thread(self, context):
118 try:
119 self.pendingcalls_submit(context.l, context.n)
120 finally:
121 with context.lock:
122 context.nFinished += 1
123 nFinished = context.nFinished
124 if False and support.verbose:
125 print("finished threads: ", nFinished)
126 if nFinished == context.nThreads:
127 context.event.set()
128
Benjamin Petersona54c9092009-01-13 02:11:23 +0000129 def test_pendingcalls_non_threaded(self):
130 #again, just using the main thread, likely they will all be dispathced at
131 #once. It is ok to ask for too many, because we loop until we find a slot.
132 #the loop can be interrupted to dispatch.
133 #there are only 32 dispatch slots, so we go for twice that!
134 l = []
135 n = 64
136 self.pendingcalls_submit(l, n)
137 self.pendingcalls_wait(l, n)
138
Martin v. Löwisc15bdef2009-05-29 14:47:46 +0000139# Bug #6012
140class Test6012(unittest.TestCase):
141 def test(self):
142 self.assertEqual(_testcapi.argparsing("Hello", "World"), 1)
Benjamin Petersona54c9092009-01-13 02:11:23 +0000143
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000144def test_main():
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +0000145 support.run_unittest(CAPITest)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000146
147 for name in dir(_testcapi):
148 if name.startswith('test_'):
149 test = getattr(_testcapi, name)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000150 if support.verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000151 print("internal", name)
Collin Winter3add4d72007-08-29 23:37:32 +0000152 test()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000153
154 # some extra thread-state tests driven via _testcapi
155 def TestThreadState():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000156 if support.verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000157 print("auto-thread-state")
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000158
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000159 idents = []
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000160
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000161 def callback():
Georg Brandl2067bfd2008-05-25 13:05:15 +0000162 idents.append(_thread.get_ident())
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000163
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000164 _testcapi._test_thread_state(callback)
165 a = b = callback
166 time.sleep(1)
167 # Check our main thread is in the list exactly 3 times.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000168 if idents.count(_thread.get_ident()) != 3:
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000169 raise support.TestFailed(
Collin Winter3add4d72007-08-29 23:37:32 +0000170 "Couldn't find main thread correctly in the list")
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000171
Victor Stinner45df8202010-04-28 22:31:17 +0000172 if threading:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000173 import _thread
Christian Heimes5e696852008-04-09 08:37:03 +0000174 import time
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000175 TestThreadState()
Georg Brandl2067bfd2008-05-25 13:05:15 +0000176 t = threading.Thread(target=TestThreadState)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000177 t.start()
178 t.join()
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000179
Martin v. Löwisc15bdef2009-05-29 14:47:46 +0000180 support.run_unittest(TestPendingCalls, Test6012)
Benjamin Petersona54c9092009-01-13 02:11:23 +0000181
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +0000182
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000183if __name__ == "__main__":
184 test_main()