blob: 7be430ce358cf245dda4d6e56ea92deb6f333255 [file] [log] [blame]
Guido van Rossumad50ca92002-12-30 22:30:22 +00001"""Generic thread tests.
2
3Meant to be used by dummy_thread and thread. To allow for different modules
4to be used, test_main() can be called with the module to use as the thread
5implementation as its sole argument.
6
7"""
8import dummy_thread as _thread
9import time
10import Queue
11import random
12import unittest
13from test import test_support
14
15
16class LockTests(unittest.TestCase):
17 """Test lock objects."""
18
19 def setUp(self):
20 # Create a lock
21 self.lock = _thread.allocate_lock()
22
23 def test_initlock(self):
24 #Make sure locks start locked
25 self.failUnless(not self.lock.locked(),
26 "Lock object is not initialized unlocked.")
27
28 def test_release(self):
29 # Test self.lock.release()
30 self.lock.acquire()
31 self.lock.release()
32 self.failUnless(not self.lock.locked(),
33 "Lock object did not release properly.")
Tim Petersf2715e02003-02-19 02:35:07 +000034
Guido van Rossumad50ca92002-12-30 22:30:22 +000035 def test_improper_release(self):
36 #Make sure release of an unlocked thread raises _thread.error
37 self.failUnlessRaises(_thread.error, self.lock.release)
38
39 def test_cond_acquire_success(self):
40 #Make sure the conditional acquiring of the lock works.
41 self.failUnless(self.lock.acquire(0),
42 "Conditional acquiring of the lock failed.")
43
44 def test_cond_acquire_fail(self):
45 #Test acquiring locked lock returns False
46 self.lock.acquire(0)
47 self.failUnless(not self.lock.acquire(0),
48 "Conditional acquiring of a locked lock incorrectly "
49 "succeeded.")
50
51 def test_uncond_acquire_success(self):
52 #Make sure unconditional acquiring of a lock works.
53 self.lock.acquire()
54 self.failUnless(self.lock.locked(),
55 "Uncondional locking failed.")
56
57 def test_uncond_acquire_return_val(self):
58 #Make sure that an unconditional locking returns True.
59 self.failUnless(self.lock.acquire(1) is True,
60 "Unconditional locking did not return True.")
Tim Petersf2715e02003-02-19 02:35:07 +000061
Guido van Rossumad50ca92002-12-30 22:30:22 +000062 def test_uncond_acquire_blocking(self):
63 #Make sure that unconditional acquiring of a locked lock blocks.
64 def delay_unlock(to_unlock, delay):
65 """Hold on to lock for a set amount of time before unlocking."""
66 time.sleep(delay)
67 to_unlock.release()
68
69 self.lock.acquire()
70 delay = 1 #In seconds
71 start_time = int(time.time())
72 _thread.start_new_thread(delay_unlock,(self.lock, delay))
73 if test_support.verbose:
74 print
75 print "*** Waiting for thread to release the lock "\
76 "(approx. %s sec.) ***" % delay
77 self.lock.acquire()
78 end_time = int(time.time())
79 if test_support.verbose:
80 print "done"
81 self.failUnless((end_time - start_time) >= delay,
82 "Blocking by unconditional acquiring failed.")
83
84class MiscTests(unittest.TestCase):
85 """Miscellaneous tests."""
86
87 def test_exit(self):
88 #Make sure _thread.exit() raises SystemExit
89 self.failUnlessRaises(SystemExit, _thread.exit)
90
91 def test_ident(self):
92 #Test sanity of _thread.get_ident()
93 self.failUnless(isinstance(_thread.get_ident(), int),
94 "_thread.get_ident() returned a non-integer")
95 self.failUnless(_thread.get_ident() != 0,
96 "_thread.get_ident() returned 0")
97
98 def test_LockType(self):
99 #Make sure _thread.LockType is the same type as _thread.allocate_locke()
100 self.failUnless(isinstance(_thread.allocate_lock(), _thread.LockType),
101 "_thread.LockType is not an instance of what is "
102 "returned by _thread.allocate_lock()")
103
104class ThreadTests(unittest.TestCase):
105 """Test thread creation."""
106
107 def test_arg_passing(self):
108 #Make sure that parameter passing works.
109 def arg_tester(queue, arg1=False, arg2=False):
110 """Use to test _thread.start_new_thread() passes args properly."""
111 queue.put((arg1, arg2))
112
113 testing_queue = Queue.Queue(1)
114 _thread.start_new_thread(arg_tester, (testing_queue, True, True))
115 result = testing_queue.get()
116 self.failUnless(result[0] and result[1],
117 "Argument passing for thread creation using tuple failed")
118 _thread.start_new_thread(arg_tester, tuple(), {'queue':testing_queue,
119 'arg1':True, 'arg2':True})
120 result = testing_queue.get()
121 self.failUnless(result[0] and result[1],
122 "Argument passing for thread creation using kwargs failed")
123 _thread.start_new_thread(arg_tester, (testing_queue, True), {'arg2':True})
124 result = testing_queue.get()
125 self.failUnless(result[0] and result[1],
126 "Argument passing for thread creation using both tuple"
127 " and kwargs failed")
Tim Petersf2715e02003-02-19 02:35:07 +0000128
Guido van Rossumad50ca92002-12-30 22:30:22 +0000129 def test_multi_creation(self):
130 #Make sure multiple threads can be created.
131 def queue_mark(queue, delay):
132 """Wait for ``delay`` seconds and then put something into ``queue``"""
133 time.sleep(delay)
134 queue.put(_thread.get_ident())
Tim Petersf2715e02003-02-19 02:35:07 +0000135
Guido van Rossumad50ca92002-12-30 22:30:22 +0000136 thread_count = 5
137 delay = 1.5
138 testing_queue = Queue.Queue(thread_count)
139 if test_support.verbose:
140 print
141 print "*** Testing multiple thread creation "\
142 "(will take approx. %s to %s sec.) ***" % (delay, thread_count)
143 for count in xrange(thread_count):
144 _thread.start_new_thread(queue_mark,
145 (testing_queue, round(random.random(), 1)))
146 time.sleep(delay)
147 if test_support.verbose:
148 print 'done'
149 self.failUnless(testing_queue.qsize() == thread_count,
Tim Petersf2715e02003-02-19 02:35:07 +0000150 "Not all %s threads executed properly after %s sec." %
Guido van Rossumad50ca92002-12-30 22:30:22 +0000151 (thread_count, delay))
152
153def test_main(imported_module=None):
154 global _thread
155 if imported_module:
156 _thread = imported_module
157 if test_support.verbose:
158 print
159 print "*** Using %s as _thread module ***" % _thread
160 suite = unittest.TestSuite()
161 suite.addTest(unittest.makeSuite(LockTests))
162 suite.addTest(unittest.makeSuite(MiscTests))
163 suite.addTest(unittest.makeSuite(ThreadTests))
164 test_support.run_suite(suite)
165
166if __name__ == '__main__':
167 test_main()