blob: ac382c14cfb33439cfe7ce8238aa122351f396ce [file] [log] [blame]
Mark Hammond3b959db2002-04-19 00:11:32 +00001# Some simple Queue module tests, plus some failure conditions
Tim Petersafe52972004-08-20 02:37:25 +00002# to ensure the Queue locks remain stable.
Mark Hammond3b959db2002-04-19 00:11:32 +00003import Queue
4import sys
5import threading
6import time
7
Barry Warsaw04f357c2002-07-23 19:04:11 +00008from test.test_support import verify, TestFailed, verbose
Mark Hammond3b959db2002-04-19 00:11:32 +00009
Tim Petersafe52972004-08-20 02:37:25 +000010QUEUE_SIZE = 5
Mark Hammond3b959db2002-04-19 00:11:32 +000011
Tim Petersafe52972004-08-20 02:37:25 +000012# A thread to run a function that unclogs a blocked Queue.
Mark Hammond3b959db2002-04-19 00:11:32 +000013class _TriggerThread(threading.Thread):
14 def __init__(self, fn, args):
15 self.fn = fn
16 self.args = args
17 self.startedEvent = threading.Event()
18 threading.Thread.__init__(self)
Tim Petersafe52972004-08-20 02:37:25 +000019
Mark Hammond3b959db2002-04-19 00:11:32 +000020 def run(self):
Tim Peters8d7626c2004-08-20 03:27:12 +000021 # The sleep isn't necessary, but is intended to give the blocking
22 # function in the main thread a chance at actually blocking before
23 # we unclog it. But if the sleep is longer than the timeout-based
24 # tests wait in their blocking functions, those tests will fail.
25 # So we give them much longer timeout values compared to the
26 # sleep here (I aimed at 10 seconds for blocking functions --
27 # they should never actually wait that long - they should make
28 # progress as soon as we call self.fn()).
29 time.sleep(0.1)
Mark Hammond3b959db2002-04-19 00:11:32 +000030 self.startedEvent.set()
31 self.fn(*self.args)
32
Tim Peters8d7626c2004-08-20 03:27:12 +000033# Execute a function that blocks, and in a separate thread, a function that
Tim Petersafe52972004-08-20 02:37:25 +000034# triggers the release. Returns the result of the blocking function.
Tim Peters8d7626c2004-08-20 03:27:12 +000035# Caution: block_func must guarantee to block until trigger_func is
36# called, and trigger_func must guarantee to change queue state so that
37# block_func can make enough progress to return. In particular, a
38# block_func that just raises an exception regardless of whether trigger_func
39# is called will lead to timing-dependent sporadic failures, and one of
40# those went rarely seen but undiagnosed for years. Now block_func
41# must be unexceptional. If block_func is supposed to raise an exception,
42# call _doExceptionalBlockingTest() instead.
Tim Petersa1d004a2002-11-15 19:08:50 +000043def _doBlockingTest(block_func, block_args, trigger_func, trigger_args):
Mark Hammond3b959db2002-04-19 00:11:32 +000044 t = _TriggerThread(trigger_func, trigger_args)
45 t.start()
Tim Peters8d7626c2004-08-20 03:27:12 +000046 result = block_func(*block_args)
47 # If block_func returned before our thread made the call, we failed!
48 if not t.startedEvent.isSet():
49 raise TestFailed("blocking function '%r' appeared not to block" %
50 block_func)
51 t.join(10) # make sure the thread terminates
52 if t.isAlive():
53 raise TestFailed("trigger function '%r' appeared to not return" %
54 trigger_func)
55 return result
56
57# Call this instead if block_func is supposed to raise an exception.
58def _doExceptionalBlockingTest(block_func, block_args, trigger_func,
59 trigger_args, expected_exception_class):
60 t = _TriggerThread(trigger_func, trigger_args)
61 t.start()
Mark Hammond3b959db2002-04-19 00:11:32 +000062 try:
Tim Peters8d7626c2004-08-20 03:27:12 +000063 try:
64 block_func(*block_args)
65 except expected_exception_class:
66 raise
67 else:
68 raise TestFailed("expected exception of kind %r" %
69 expected_exception_class)
Mark Hammond3b959db2002-04-19 00:11:32 +000070 finally:
Tim Peters8d7626c2004-08-20 03:27:12 +000071 t.join(10) # make sure the thread terminates
Mark Hammond3b959db2002-04-19 00:11:32 +000072 if t.isAlive():
Tim Petersa1d004a2002-11-15 19:08:50 +000073 raise TestFailed("trigger function '%r' appeared to not return" %
74 trigger_func)
Tim Peters8d7626c2004-08-20 03:27:12 +000075 if not t.startedEvent.isSet():
76 raise TestFailed("trigger thread ended but event never set")
Mark Hammond3b959db2002-04-19 00:11:32 +000077
78# A Queue subclass that can provoke failure at a moment's notice :)
79class FailingQueueException(Exception):
80 pass
81
82class FailingQueue(Queue.Queue):
83 def __init__(self, *args):
84 self.fail_next_put = False
85 self.fail_next_get = False
86 Queue.Queue.__init__(self, *args)
87 def _put(self, item):
88 if self.fail_next_put:
89 self.fail_next_put = False
90 raise FailingQueueException, "You Lose"
91 return Queue.Queue._put(self, item)
92 def _get(self):
93 if self.fail_next_get:
94 self.fail_next_get = False
95 raise FailingQueueException, "You Lose"
96 return Queue.Queue._get(self)
97
98def FailingQueueTest(q):
99 if not q.empty():
100 raise RuntimeError, "Call this function with an empty queue"
Tim Petersafe52972004-08-20 02:37:25 +0000101 for i in range(QUEUE_SIZE-1):
Mark Hammond3b959db2002-04-19 00:11:32 +0000102 q.put(i)
Mark Hammond3b959db2002-04-19 00:11:32 +0000103 # Test a failing non-blocking put.
Martin v. Löwis77ac4292002-10-15 15:11:13 +0000104 q.fail_next_put = True
Mark Hammond3b959db2002-04-19 00:11:32 +0000105 try:
106 q.put("oops", block=0)
107 raise TestFailed("The queue didn't fail when it should have")
108 except FailingQueueException:
109 pass
Martin v. Löwis77ac4292002-10-15 15:11:13 +0000110 q.fail_next_put = True
111 try:
112 q.put("oops", timeout=0.1)
113 raise TestFailed("The queue didn't fail when it should have")
114 except FailingQueueException:
115 pass
Mark Hammond3b959db2002-04-19 00:11:32 +0000116 q.put("last")
117 verify(q.full(), "Queue should be full")
Mark Hammond3b959db2002-04-19 00:11:32 +0000118 # Test a failing blocking put
Martin v. Löwis77ac4292002-10-15 15:11:13 +0000119 q.fail_next_put = True
Mark Hammond3b959db2002-04-19 00:11:32 +0000120 try:
Tim Petersafe52972004-08-20 02:37:25 +0000121 _doBlockingTest(q.put, ("full",), q.get, ())
Mark Hammond3b959db2002-04-19 00:11:32 +0000122 raise TestFailed("The queue didn't fail when it should have")
123 except FailingQueueException:
124 pass
125 # Check the Queue isn't damaged.
126 # put failed, but get succeeded - re-add
127 q.put("last")
Martin v. Löwis77ac4292002-10-15 15:11:13 +0000128 # Test a failing timeout put
129 q.fail_next_put = True
130 try:
Tim Peters8d7626c2004-08-20 03:27:12 +0000131 _doExceptionalBlockingTest(q.put, ("full", True, 10), q.get, (),
132 FailingQueueException)
Martin v. Löwis77ac4292002-10-15 15:11:13 +0000133 raise TestFailed("The queue didn't fail when it should have")
134 except FailingQueueException:
135 pass
136 # Check the Queue isn't damaged.
137 # put failed, but get succeeded - re-add
138 q.put("last")
Mark Hammond3b959db2002-04-19 00:11:32 +0000139 verify(q.full(), "Queue should be full")
140 q.get()
141 verify(not q.full(), "Queue should not be full")
142 q.put("last")
143 verify(q.full(), "Queue should be full")
144 # Test a blocking put
145 _doBlockingTest( q.put, ("full",), q.get, ())
146 # Empty it
Tim Petersafe52972004-08-20 02:37:25 +0000147 for i in range(QUEUE_SIZE):
Mark Hammond3b959db2002-04-19 00:11:32 +0000148 q.get()
149 verify(q.empty(), "Queue should be empty")
150 q.put("first")
151 q.fail_next_get = True
152 try:
153 q.get()
154 raise TestFailed("The queue didn't fail when it should have")
155 except FailingQueueException:
156 pass
157 verify(not q.empty(), "Queue should not be empty")
Martin v. Löwis77ac4292002-10-15 15:11:13 +0000158 q.fail_next_get = True
159 try:
160 q.get(timeout=0.1)
161 raise TestFailed("The queue didn't fail when it should have")
162 except FailingQueueException:
163 pass
164 verify(not q.empty(), "Queue should not be empty")
Mark Hammond3b959db2002-04-19 00:11:32 +0000165 q.get()
166 verify(q.empty(), "Queue should be empty")
167 q.fail_next_get = True
168 try:
Tim Peters8d7626c2004-08-20 03:27:12 +0000169 _doExceptionalBlockingTest(q.get, (), q.put, ('empty',),
170 FailingQueueException)
Mark Hammond3b959db2002-04-19 00:11:32 +0000171 raise TestFailed("The queue didn't fail when it should have")
172 except FailingQueueException:
173 pass
174 # put succeeded, but get failed.
175 verify(not q.empty(), "Queue should not be empty")
176 q.get()
177 verify(q.empty(), "Queue should be empty")
178
179def SimpleQueueTest(q):
180 if not q.empty():
181 raise RuntimeError, "Call this function with an empty queue"
182 # I guess we better check things actually queue correctly a little :)
183 q.put(111)
184 q.put(222)
Tim Petersa1d004a2002-11-15 19:08:50 +0000185 verify(q.get() == 111 and q.get() == 222,
186 "Didn't seem to queue the correct data!")
Tim Petersafe52972004-08-20 02:37:25 +0000187 for i in range(QUEUE_SIZE-1):
Mark Hammond3b959db2002-04-19 00:11:32 +0000188 q.put(i)
Tim Peters8d7626c2004-08-20 03:27:12 +0000189 verify(not q.empty(), "Queue should not be empty")
Mark Hammond3b959db2002-04-19 00:11:32 +0000190 verify(not q.full(), "Queue should not be full")
191 q.put("last")
192 verify(q.full(), "Queue should be full")
193 try:
194 q.put("full", block=0)
195 raise TestFailed("Didn't appear to block with a full queue")
196 except Queue.Full:
197 pass
Martin v. Löwis77ac4292002-10-15 15:11:13 +0000198 try:
Tim Peters8d7626c2004-08-20 03:27:12 +0000199 q.put("full", timeout=0.01)
Martin v. Löwis77ac4292002-10-15 15:11:13 +0000200 raise TestFailed("Didn't appear to time-out with a full queue")
201 except Queue.Full:
202 pass
Mark Hammond3b959db2002-04-19 00:11:32 +0000203 # Test a blocking put
Tim Petersafe52972004-08-20 02:37:25 +0000204 _doBlockingTest(q.put, ("full",), q.get, ())
Tim Peters8d7626c2004-08-20 03:27:12 +0000205 _doBlockingTest(q.put, ("full", True, 10), q.get, ())
Mark Hammond3b959db2002-04-19 00:11:32 +0000206 # Empty it
Tim Petersafe52972004-08-20 02:37:25 +0000207 for i in range(QUEUE_SIZE):
Mark Hammond3b959db2002-04-19 00:11:32 +0000208 q.get()
209 verify(q.empty(), "Queue should be empty")
210 try:
211 q.get(block=0)
212 raise TestFailed("Didn't appear to block with an empty queue")
213 except Queue.Empty:
214 pass
Martin v. Löwis77ac4292002-10-15 15:11:13 +0000215 try:
Tim Peters8d7626c2004-08-20 03:27:12 +0000216 q.get(timeout=0.01)
Martin v. Löwis77ac4292002-10-15 15:11:13 +0000217 raise TestFailed("Didn't appear to time-out with an empty queue")
218 except Queue.Empty:
219 pass
Mark Hammond3b959db2002-04-19 00:11:32 +0000220 # Test a blocking get
Tim Petersa1d004a2002-11-15 19:08:50 +0000221 _doBlockingTest(q.get, (), q.put, ('empty',))
Tim Peters8d7626c2004-08-20 03:27:12 +0000222 _doBlockingTest(q.get, (True, 10), q.put, ('empty',))
Mark Hammond3b959db2002-04-19 00:11:32 +0000223
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000224cum = 0
225cumlock = threading.Lock()
226
227def worker(q):
228 global cum
229 while True:
230 x = q.get()
231 if x is None:
232 q.task_done()
233 return
234 cumlock.acquire()
235 try:
236 cum += x
237 finally:
238 cumlock.release()
239 q.task_done()
240
241def QueueJoinTest(q):
242 global cum
243 cum = 0
244 for i in (0,1):
245 threading.Thread(target=worker, args=(q,)).start()
246 for i in xrange(100):
247 q.put(i)
248 q.join()
249 verify(cum==sum(range(100)), "q.join() did not block until all tasks were done")
250 for i in (0,1):
251 q.put(None) # instruct the threads to close
252 q.join() # verify that you can join twice
253
254def QueueTaskDoneTest(q):
255 try:
256 q.task_done()
257 except ValueError:
258 pass
259 else:
260 raise TestFailed("Did not detect task count going negative")
261
Mark Hammond3b959db2002-04-19 00:11:32 +0000262def test():
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000263 q = Queue.Queue()
264 QueueTaskDoneTest(q)
265 QueueJoinTest(q)
266 QueueJoinTest(q)
267 QueueTaskDoneTest(q)
268
Tim Petersafe52972004-08-20 02:37:25 +0000269 q = Queue.Queue(QUEUE_SIZE)
Mark Hammond3b959db2002-04-19 00:11:32 +0000270 # Do it a couple of times on the same queue
271 SimpleQueueTest(q)
272 SimpleQueueTest(q)
273 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000274 print("Simple Queue tests seemed to work")
Tim Petersafe52972004-08-20 02:37:25 +0000275 q = FailingQueue(QUEUE_SIZE)
Mark Hammond3b959db2002-04-19 00:11:32 +0000276 FailingQueueTest(q)
277 FailingQueueTest(q)
278 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000279 print("Failing Queue tests seemed to work")
Mark Hammond3b959db2002-04-19 00:11:32 +0000280
281test()