blob: 2a76cdac0bd22f104879299da4ad1942bd278ca7 [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)
Raymond Hettinger9e1bc982008-01-16 23:40:45 +0000184 q.put(333)
Mark Hammond3b959db2002-04-19 00:11:32 +0000185 q.put(222)
Raymond Hettinger9e1bc982008-01-16 23:40:45 +0000186 target_order = dict(Queue = [111, 333, 222],
187 LifoQueue = [222, 333, 111],
188 PriorityQueue = [111, 222, 333])
189 actual_order = [q.get(), q.get(), q.get()]
190 verify(actual_order == target_order[q.__class__.__name__],
Tim Petersa1d004a2002-11-15 19:08:50 +0000191 "Didn't seem to queue the correct data!")
Tim Petersafe52972004-08-20 02:37:25 +0000192 for i in range(QUEUE_SIZE-1):
Mark Hammond3b959db2002-04-19 00:11:32 +0000193 q.put(i)
Tim Peters8d7626c2004-08-20 03:27:12 +0000194 verify(not q.empty(), "Queue should not be empty")
Mark Hammond3b959db2002-04-19 00:11:32 +0000195 verify(not q.full(), "Queue should not be full")
196 q.put("last")
197 verify(q.full(), "Queue should be full")
198 try:
199 q.put("full", block=0)
200 raise TestFailed("Didn't appear to block with a full queue")
201 except Queue.Full:
202 pass
Martin v. Löwis77ac4292002-10-15 15:11:13 +0000203 try:
Tim Peters8d7626c2004-08-20 03:27:12 +0000204 q.put("full", timeout=0.01)
Martin v. Löwis77ac4292002-10-15 15:11:13 +0000205 raise TestFailed("Didn't appear to time-out with a full queue")
206 except Queue.Full:
207 pass
Mark Hammond3b959db2002-04-19 00:11:32 +0000208 # Test a blocking put
Tim Petersafe52972004-08-20 02:37:25 +0000209 _doBlockingTest(q.put, ("full",), q.get, ())
Tim Peters8d7626c2004-08-20 03:27:12 +0000210 _doBlockingTest(q.put, ("full", True, 10), q.get, ())
Mark Hammond3b959db2002-04-19 00:11:32 +0000211 # Empty it
Tim Petersafe52972004-08-20 02:37:25 +0000212 for i in range(QUEUE_SIZE):
Mark Hammond3b959db2002-04-19 00:11:32 +0000213 q.get()
214 verify(q.empty(), "Queue should be empty")
215 try:
216 q.get(block=0)
217 raise TestFailed("Didn't appear to block with an empty queue")
218 except Queue.Empty:
219 pass
Martin v. Löwis77ac4292002-10-15 15:11:13 +0000220 try:
Tim Peters8d7626c2004-08-20 03:27:12 +0000221 q.get(timeout=0.01)
Martin v. Löwis77ac4292002-10-15 15:11:13 +0000222 raise TestFailed("Didn't appear to time-out with an empty queue")
223 except Queue.Empty:
224 pass
Mark Hammond3b959db2002-04-19 00:11:32 +0000225 # Test a blocking get
Tim Petersa1d004a2002-11-15 19:08:50 +0000226 _doBlockingTest(q.get, (), q.put, ('empty',))
Tim Peters8d7626c2004-08-20 03:27:12 +0000227 _doBlockingTest(q.get, (True, 10), q.put, ('empty',))
Mark Hammond3b959db2002-04-19 00:11:32 +0000228
Raymond Hettingerfd3fcf02006-03-24 20:43:29 +0000229cum = 0
230cumlock = threading.Lock()
231
232def worker(q):
233 global cum
234 while True:
235 x = q.get()
Raymond Hettingerc4e94b92006-03-25 12:15:04 +0000236 if x is None:
237 q.task_done()
238 return
Raymond Hettingerfd3fcf02006-03-24 20:43:29 +0000239 cumlock.acquire()
240 try:
241 cum += x
242 finally:
243 cumlock.release()
244 q.task_done()
Tim Peterse33901e2006-03-25 01:50:43 +0000245
Raymond Hettingerfd3fcf02006-03-24 20:43:29 +0000246def QueueJoinTest(q):
247 global cum
248 cum = 0
249 for i in (0,1):
Raymond Hettingerc4e94b92006-03-25 12:15:04 +0000250 threading.Thread(target=worker, args=(q,)).start()
Raymond Hettingerfd3fcf02006-03-24 20:43:29 +0000251 for i in xrange(100):
252 q.put(i)
253 q.join()
254 verify(cum==sum(range(100)), "q.join() did not block until all tasks were done")
Raymond Hettingerc4e94b92006-03-25 12:15:04 +0000255 for i in (0,1):
256 q.put(None) # instruct the threads to close
257 q.join() # verify that you can join twice
258
Georg Brandlbaf05b72006-03-25 13:12:56 +0000259def QueueTaskDoneTest(q):
Raymond Hettingerc4e94b92006-03-25 12:15:04 +0000260 try:
261 q.task_done()
262 except ValueError:
263 pass
264 else:
265 raise TestFailed("Did not detect task count going negative")
Raymond Hettingerfd3fcf02006-03-24 20:43:29 +0000266
Mark Hammond3b959db2002-04-19 00:11:32 +0000267def test():
Raymond Hettinger9e1bc982008-01-16 23:40:45 +0000268 for Q in Queue.Queue, Queue.LifoQueue, Queue.PriorityQueue:
269 q = Q()
270 QueueTaskDoneTest(q)
271 QueueJoinTest(q)
272 QueueJoinTest(q)
273 QueueTaskDoneTest(q)
Raymond Hettingerfd3fcf02006-03-24 20:43:29 +0000274
Raymond Hettinger9e1bc982008-01-16 23:40:45 +0000275 q = Q(QUEUE_SIZE)
276 # Do it a couple of times on the same queue
277 SimpleQueueTest(q)
278 SimpleQueueTest(q)
279 if verbose:
280 print "Simple Queue tests seemed to work for", Q.__name__
281
Tim Petersafe52972004-08-20 02:37:25 +0000282 q = FailingQueue(QUEUE_SIZE)
Mark Hammond3b959db2002-04-19 00:11:32 +0000283 FailingQueueTest(q)
284 FailingQueueTest(q)
285 if verbose:
286 print "Failing Queue tests seemed to work"
287
288test()