blob: eaedebc2aa53a93df984e150d26e3c81bf4d089c [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
Georg Brandld22b4662008-02-02 11:39:29 +00007import unittest
8from test import test_support
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
Georg Brandlb7090772008-02-05 19:58:17 +000012def qfull(q):
13 return q.maxsize > 0 and q.qsize() == q.maxsize
14
15
Tim Petersafe52972004-08-20 02:37:25 +000016# A thread to run a function that unclogs a blocked Queue.
Mark Hammond3b959db2002-04-19 00:11:32 +000017class _TriggerThread(threading.Thread):
18 def __init__(self, fn, args):
19 self.fn = fn
20 self.args = args
21 self.startedEvent = threading.Event()
22 threading.Thread.__init__(self)
Tim Petersafe52972004-08-20 02:37:25 +000023
Mark Hammond3b959db2002-04-19 00:11:32 +000024 def run(self):
Tim Peters8d7626c2004-08-20 03:27:12 +000025 # The sleep isn't necessary, but is intended to give the blocking
26 # function in the main thread a chance at actually blocking before
27 # we unclog it. But if the sleep is longer than the timeout-based
28 # tests wait in their blocking functions, those tests will fail.
29 # So we give them much longer timeout values compared to the
30 # sleep here (I aimed at 10 seconds for blocking functions --
31 # they should never actually wait that long - they should make
32 # progress as soon as we call self.fn()).
33 time.sleep(0.1)
Mark Hammond3b959db2002-04-19 00:11:32 +000034 self.startedEvent.set()
35 self.fn(*self.args)
36
Tim Peters8d7626c2004-08-20 03:27:12 +000037
Georg Brandld22b4662008-02-02 11:39:29 +000038# Execute a function that blocks, and in a separate thread, a function that
39# triggers the release. Returns the result of the blocking function. Caution:
40# block_func must guarantee to block until trigger_func is called, and
41# trigger_func must guarantee to change queue state so that block_func can make
42# enough progress to return. In particular, a block_func that just raises an
43# exception regardless of whether trigger_func is called will lead to
44# timing-dependent sporadic failures, and one of those went rarely seen but
45# undiagnosed for years. Now block_func must be unexceptional. If block_func
46# is supposed to raise an exception, call do_exceptional_blocking_test()
47# instead.
48
49class BlockingTestMixin:
50
51 def do_blocking_test(self, block_func, block_args, trigger_func, trigger_args):
52 self.t = _TriggerThread(trigger_func, trigger_args)
53 self.t.start()
54 self.result = block_func(*block_args)
55 # If block_func returned before our thread made the call, we failed!
56 if not self.t.startedEvent.isSet():
57 self.fail("blocking function '%r' appeared not to block" %
58 block_func)
59 self.t.join(10) # make sure the thread terminates
60 if self.t.isAlive():
61 self.fail("trigger function '%r' appeared to not return" %
62 trigger_func)
63 return self.result
64
65 # Call this instead if block_func is supposed to raise an exception.
66 def do_exceptional_blocking_test(self,block_func, block_args, trigger_func,
67 trigger_args, expected_exception_class):
68 self.t = _TriggerThread(trigger_func, trigger_args)
69 self.t.start()
Tim Peters8d7626c2004-08-20 03:27:12 +000070 try:
Georg Brandld22b4662008-02-02 11:39:29 +000071 try:
72 block_func(*block_args)
73 except expected_exception_class:
74 raise
75 else:
76 self.fail("expected exception of kind %r" %
77 expected_exception_class)
78 finally:
79 self.t.join(10) # make sure the thread terminates
80 if self.t.isAlive():
81 self.fail("trigger function '%r' appeared to not return" %
82 trigger_func)
83 if not self.t.startedEvent.isSet():
84 self.fail("trigger thread ended but event never set")
85
86
87class BaseQueueTest(unittest.TestCase, BlockingTestMixin):
88 def setUp(self):
89 self.cum = 0
90 self.cumlock = threading.Lock()
91
92 def simple_queue_test(self, q):
Georg Brandlb7090772008-02-05 19:58:17 +000093 if q.qsize():
Georg Brandld22b4662008-02-02 11:39:29 +000094 raise RuntimeError, "Call this function with an empty queue"
95 # I guess we better check things actually queue correctly a little :)
96 q.put(111)
97 q.put(333)
98 q.put(222)
99 target_order = dict(Queue = [111, 333, 222],
100 LifoQueue = [222, 333, 111],
101 PriorityQueue = [111, 222, 333])
102 actual_order = [q.get(), q.get(), q.get()]
103 self.assertEquals(actual_order, target_order[q.__class__.__name__],
104 "Didn't seem to queue the correct data!")
105 for i in range(QUEUE_SIZE-1):
106 q.put(i)
Georg Brandlb7090772008-02-05 19:58:17 +0000107 self.assert_(q.qsize(), "Queue should not be empty")
108 self.assert_(not qfull(q), "Queue should not be full")
Georg Brandld22b4662008-02-02 11:39:29 +0000109 q.put("last")
Georg Brandlb7090772008-02-05 19:58:17 +0000110 self.assert_(qfull(q), "Queue should be full")
Georg Brandld22b4662008-02-02 11:39:29 +0000111 try:
112 q.put("full", block=0)
113 self.fail("Didn't appear to block with a full queue")
114 except Queue.Full:
115 pass
116 try:
117 q.put("full", timeout=0.01)
118 self.fail("Didn't appear to time-out with a full queue")
119 except Queue.Full:
120 pass
121 # Test a blocking put
122 self.do_blocking_test(q.put, ("full",), q.get, ())
123 self.do_blocking_test(q.put, ("full", True, 10), q.get, ())
124 # Empty it
125 for i in range(QUEUE_SIZE):
126 q.get()
Georg Brandlb7090772008-02-05 19:58:17 +0000127 self.assert_(not q.qsize(), "Queue should be empty")
Georg Brandld22b4662008-02-02 11:39:29 +0000128 try:
129 q.get(block=0)
130 self.fail("Didn't appear to block with an empty queue")
131 except Queue.Empty:
132 pass
133 try:
134 q.get(timeout=0.01)
135 self.fail("Didn't appear to time-out with an empty queue")
136 except Queue.Empty:
137 pass
138 # Test a blocking get
139 self.do_blocking_test(q.get, (), q.put, ('empty',))
140 self.do_blocking_test(q.get, (True, 10), q.put, ('empty',))
141
142
143 def worker(self, q):
144 while True:
Georg Brandlcafb7102008-02-02 23:59:21 +0000145 x = q.get()
146 if x is None:
Georg Brandld22b4662008-02-02 11:39:29 +0000147 q.task_done()
148 return
Brett Cannon4b7deed2008-02-03 02:43:01 +0000149 with self.cumlock:
Georg Brandlcafb7102008-02-02 23:59:21 +0000150 self.cum += x
Georg Brandld22b4662008-02-02 11:39:29 +0000151 q.task_done()
152
153 def queue_join_test(self, q):
154 self.cum = 0
155 for i in (0,1):
156 threading.Thread(target=self.worker, args=(q,)).start()
157 for i in xrange(100):
158 q.put(i)
159 q.join()
160 self.assertEquals(self.cum, sum(range(100)),
Georg Brandlcafb7102008-02-02 23:59:21 +0000161 "q.join() did not block until all tasks were done")
Georg Brandld22b4662008-02-02 11:39:29 +0000162 for i in (0,1):
163 q.put(None) # instruct the threads to close
164 q.join() # verify that you can join twice
165
166 def test_queue_task_done(self):
167 # Test to make sure a queue task completed successfully.
168 q = self.type2test()
169 try:
170 q.task_done()
171 except ValueError:
172 pass
Tim Peters8d7626c2004-08-20 03:27:12 +0000173 else:
Georg Brandld22b4662008-02-02 11:39:29 +0000174 self.fail("Did not detect task count going negative")
175
176 def test_queue_join(self):
177 # Test that a queue join()s successfully, and before anything else
178 # (done twice for insurance).
179 q = self.type2test()
180 self.queue_join_test(q)
181 self.queue_join_test(q)
182 try:
183 q.task_done()
184 except ValueError:
185 pass
186 else:
187 self.fail("Did not detect task count going negative")
188
189 def test_simple_queue(self):
190 # Do it a couple of times on the same queue.
191 # Done twice to make sure works with same instance reused.
192 q = self.type2test(QUEUE_SIZE)
193 self.simple_queue_test(q)
194 self.simple_queue_test(q)
195
196
197class QueueTest(BaseQueueTest):
198 type2test = Queue.Queue
199
200class LifoQueueTest(BaseQueueTest):
201 type2test = Queue.LifoQueue
202
203class PriorityQueueTest(BaseQueueTest):
204 type2test = Queue.PriorityQueue
205
206
Mark Hammond3b959db2002-04-19 00:11:32 +0000207
208# A Queue subclass that can provoke failure at a moment's notice :)
209class FailingQueueException(Exception):
210 pass
211
212class FailingQueue(Queue.Queue):
213 def __init__(self, *args):
214 self.fail_next_put = False
215 self.fail_next_get = False
216 Queue.Queue.__init__(self, *args)
217 def _put(self, item):
218 if self.fail_next_put:
219 self.fail_next_put = False
220 raise FailingQueueException, "You Lose"
221 return Queue.Queue._put(self, item)
222 def _get(self):
223 if self.fail_next_get:
224 self.fail_next_get = False
225 raise FailingQueueException, "You Lose"
226 return Queue.Queue._get(self)
227
Georg Brandld22b4662008-02-02 11:39:29 +0000228class FailingQueueTest(unittest.TestCase, BlockingTestMixin):
Mark Hammond3b959db2002-04-19 00:11:32 +0000229
Georg Brandld22b4662008-02-02 11:39:29 +0000230 def failing_queue_test(self, q):
Georg Brandlb7090772008-02-05 19:58:17 +0000231 if q.qsize():
Georg Brandld22b4662008-02-02 11:39:29 +0000232 raise RuntimeError, "Call this function with an empty queue"
233 for i in range(QUEUE_SIZE-1):
234 q.put(i)
235 # Test a failing non-blocking put.
236 q.fail_next_put = True
Raymond Hettingerfd3fcf02006-03-24 20:43:29 +0000237 try:
Georg Brandld22b4662008-02-02 11:39:29 +0000238 q.put("oops", block=0)
239 self.fail("The queue didn't fail when it should have")
240 except FailingQueueException:
241 pass
242 q.fail_next_put = True
243 try:
244 q.put("oops", timeout=0.1)
245 self.fail("The queue didn't fail when it should have")
246 except FailingQueueException:
247 pass
248 q.put("last")
Georg Brandlb7090772008-02-05 19:58:17 +0000249 self.assert_(qfull(q), "Queue should be full")
Georg Brandld22b4662008-02-02 11:39:29 +0000250 # Test a failing blocking put
251 q.fail_next_put = True
252 try:
253 self.do_blocking_test(q.put, ("full",), q.get, ())
254 self.fail("The queue didn't fail when it should have")
255 except FailingQueueException:
256 pass
257 # Check the Queue isn't damaged.
258 # put failed, but get succeeded - re-add
259 q.put("last")
260 # Test a failing timeout put
261 q.fail_next_put = True
262 try:
263 self.do_exceptional_blocking_test(q.put, ("full", True, 10), q.get, (),
264 FailingQueueException)
265 self.fail("The queue didn't fail when it should have")
266 except FailingQueueException:
267 pass
268 # Check the Queue isn't damaged.
269 # put failed, but get succeeded - re-add
270 q.put("last")
Georg Brandlb7090772008-02-05 19:58:17 +0000271 self.assert_(qfull(q), "Queue should be full")
Georg Brandld22b4662008-02-02 11:39:29 +0000272 q.get()
Georg Brandlb7090772008-02-05 19:58:17 +0000273 self.assert_(not qfull(q), "Queue should not be full")
Georg Brandld22b4662008-02-02 11:39:29 +0000274 q.put("last")
Georg Brandlb7090772008-02-05 19:58:17 +0000275 self.assert_(qfull(q), "Queue should be full")
Georg Brandld22b4662008-02-02 11:39:29 +0000276 # Test a blocking put
277 self.do_blocking_test(q.put, ("full",), q.get, ())
278 # Empty it
279 for i in range(QUEUE_SIZE):
280 q.get()
Georg Brandlb7090772008-02-05 19:58:17 +0000281 self.assert_(not q.qsize(), "Queue should be empty")
Georg Brandld22b4662008-02-02 11:39:29 +0000282 q.put("first")
283 q.fail_next_get = True
284 try:
285 q.get()
286 self.fail("The queue didn't fail when it should have")
287 except FailingQueueException:
288 pass
Georg Brandlb7090772008-02-05 19:58:17 +0000289 self.assert_(q.qsize(), "Queue should not be empty")
Georg Brandld22b4662008-02-02 11:39:29 +0000290 q.fail_next_get = True
291 try:
292 q.get(timeout=0.1)
293 self.fail("The queue didn't fail when it should have")
294 except FailingQueueException:
295 pass
Georg Brandlb7090772008-02-05 19:58:17 +0000296 self.assert_(q.qsize(), "Queue should not be empty")
Georg Brandld22b4662008-02-02 11:39:29 +0000297 q.get()
Georg Brandlb7090772008-02-05 19:58:17 +0000298 self.assert_(not q.qsize(), "Queue should be empty")
Georg Brandld22b4662008-02-02 11:39:29 +0000299 q.fail_next_get = True
300 try:
301 self.do_exceptional_blocking_test(q.get, (), q.put, ('empty',),
302 FailingQueueException)
303 self.fail("The queue didn't fail when it should have")
304 except FailingQueueException:
305 pass
306 # put succeeded, but get failed.
Georg Brandlb7090772008-02-05 19:58:17 +0000307 self.assert_(q.qsize(), "Queue should not be empty")
Georg Brandld22b4662008-02-02 11:39:29 +0000308 q.get()
Georg Brandlb7090772008-02-05 19:58:17 +0000309 self.assert_(not q.qsize(), "Queue should be empty")
Tim Peterse33901e2006-03-25 01:50:43 +0000310
Georg Brandld22b4662008-02-02 11:39:29 +0000311 def test_failing_queue(self):
312 # Test to make sure a queue is functioning correctly.
313 # Done twice to the same instance.
314 q = FailingQueue(QUEUE_SIZE)
315 self.failing_queue_test(q)
316 self.failing_queue_test(q)
Raymond Hettingerc4e94b92006-03-25 12:15:04 +0000317
Raymond Hettingerfd3fcf02006-03-24 20:43:29 +0000318
Georg Brandld22b4662008-02-02 11:39:29 +0000319def test_main():
320 test_support.run_unittest(QueueTest, LifoQueueTest, PriorityQueueTest,
321 FailingQueueTest)
Raymond Hettingerfd3fcf02006-03-24 20:43:29 +0000322
Raymond Hettinger9e1bc982008-01-16 23:40:45 +0000323
Georg Brandld22b4662008-02-02 11:39:29 +0000324if __name__ == "__main__":
325 test_main()