blob: 01b7050d9f9020b214529429d4e6cdcd93063ea9 [file] [log] [blame]
Georg Brandl9f2b93e2007-08-24 18:07:52 +00001import unittest
2from test import test_support
Jeffrey Yasskincf26f542008-03-21 05:02:44 +00003from contextlib import closing, nested
Neal Norwitzbb89e682008-03-25 07:00:39 +00004import gc
Jeffrey Yasskincf26f542008-03-21 05:02:44 +00005import pickle
6import select
Guido van Rossum4f17e3e1995-03-16 15:07:38 +00007import signal
Jeffrey Yasskin413f5882008-03-21 18:25:06 +00008import subprocess
Jeffrey Yasskincf26f542008-03-21 05:02:44 +00009import traceback
Christian Heimesacfd8ed2008-02-28 21:00:45 +000010import sys, os, time, errno
11
12if sys.platform[:3] in ('win', 'os2') or sys.platform == 'riscos':
13 raise test_support.TestSkipped("Can't test signal on %s" % \
14 sys.platform)
15
Guido van Rossumcc5a91d1997-04-16 00:29:15 +000016
Armin Rigo8b2cbfd2004-08-07 21:27:43 +000017class HandlerBCalled(Exception):
18 pass
Guido van Rossum4f17e3e1995-03-16 15:07:38 +000019
Jeffrey Yasskincf26f542008-03-21 05:02:44 +000020
21def exit_subprocess():
22 """Use os._exit(0) to exit the current subprocess.
23
24 Otherwise, the test catches the SystemExit and continues executing
25 in parallel with the original test, so you wind up with an
26 exponential number of tests running concurrently.
27 """
28 os._exit(0)
29
30
Jeffrey Yasskinab561312008-04-02 04:07:44 +000031def ignoring_eintr(__func, *args, **kwargs):
32 try:
33 return __func(*args, **kwargs)
Jeffrey Yasskin2b860db2008-04-04 04:51:19 +000034 except EnvironmentError as e:
Jeffrey Yasskine71d8122008-04-04 16:48:19 +000035 if e.errno != errno.EINTR:
Jeffrey Yasskinab561312008-04-02 04:07:44 +000036 raise
37 return None
38
39
Georg Brandl9f2b93e2007-08-24 18:07:52 +000040class InterProcessSignalTests(unittest.TestCase):
41 MAX_DURATION = 20 # Entire test should last at most 20 sec.
Guido van Rossum4f17e3e1995-03-16 15:07:38 +000042
Neal Norwitzbb89e682008-03-25 07:00:39 +000043 def setUp(self):
44 self.using_gc = gc.isenabled()
45 gc.disable()
46
47 def tearDown(self):
48 if self.using_gc:
49 gc.enable()
50
Jeffrey Yasskinee767772008-04-06 23:04:28 +000051 def format_frame(self, frame, limit=None):
52 return ''.join(traceback.format_stack(frame, limit=limit))
53
54 def handlerA(self, signum, frame):
Georg Brandl9f2b93e2007-08-24 18:07:52 +000055 self.a_called = True
56 if test_support.verbose:
Jeffrey Yasskinee767772008-04-06 23:04:28 +000057 print "handlerA invoked from signal %s at:\n%s" % (
58 signum, self.format_frame(frame, limit=1))
Guido van Rossum4f17e3e1995-03-16 15:07:38 +000059
Jeffrey Yasskinee767772008-04-06 23:04:28 +000060 def handlerB(self, signum, frame):
Georg Brandl9f2b93e2007-08-24 18:07:52 +000061 self.b_called = True
62 if test_support.verbose:
Jeffrey Yasskinee767772008-04-06 23:04:28 +000063 print "handlerB invoked from signal %s at:\n%s" % (
64 signum, self.format_frame(frame, limit=1))
65 raise HandlerBCalled(signum, self.format_frame(frame))
Neal Norwitz9730bcb2006-01-23 07:50:06 +000066
Jeffrey Yasskin413f5882008-03-21 18:25:06 +000067 def wait(self, child):
68 """Wait for child to finish, ignoring EINTR."""
Jeffrey Yasskincf26f542008-03-21 05:02:44 +000069 while True:
70 try:
Jeffrey Yasskin413f5882008-03-21 18:25:06 +000071 child.wait()
Jeffrey Yasskin6cda88e2008-03-21 05:51:37 +000072 return
Jeffrey Yasskincf26f542008-03-21 05:02:44 +000073 except OSError as e:
74 if e.errno != errno.EINTR:
75 raise
Fred Drake004d5e62000-10-23 17:22:08 +000076
Jeffrey Yasskincf26f542008-03-21 05:02:44 +000077 def run_test(self):
78 # Install handlers. This function runs in a sub-process, so we
79 # don't worry about re-setting the default handlers.
80 signal.signal(signal.SIGHUP, self.handlerA)
81 signal.signal(signal.SIGUSR1, self.handlerB)
82 signal.signal(signal.SIGUSR2, signal.SIG_IGN)
83 signal.signal(signal.SIGALRM, signal.default_int_handler)
Michael W. Hudson5c26e862004-06-11 18:09:28 +000084
Jeffrey Yasskincf26f542008-03-21 05:02:44 +000085 # Variables the signals will modify:
86 self.a_called = False
87 self.b_called = False
Tim Peters1742f332006-08-12 04:42:47 +000088
Jeffrey Yasskincf26f542008-03-21 05:02:44 +000089 # Let the sub-processes know who to send signals to.
90 pid = os.getpid()
Georg Brandl9f2b93e2007-08-24 18:07:52 +000091 if test_support.verbose:
92 print "test runner's pid is", pid
Tim Peters1742f332006-08-12 04:42:47 +000093
Jeffrey Yasskinab561312008-04-02 04:07:44 +000094 child = ignoring_eintr(subprocess.Popen, ['kill', '-HUP', str(pid)])
95 if child:
96 self.wait(child)
97 if not self.a_called:
98 time.sleep(1) # Give the signal time to be delivered.
Jeffrey Yasskincf26f542008-03-21 05:02:44 +000099 self.assertTrue(self.a_called)
100 self.assertFalse(self.b_called)
101 self.a_called = False
Tim Peters1742f332006-08-12 04:42:47 +0000102
Jeffrey Yasskinee767772008-04-06 23:04:28 +0000103 # Make sure the signal isn't delivered while the previous
104 # Popen object is being destroyed, because __del__ swallows
105 # exceptions.
106 del child
Georg Brandl9f2b93e2007-08-24 18:07:52 +0000107 try:
Jeffrey Yasskin413f5882008-03-21 18:25:06 +0000108 child = subprocess.Popen(['kill', '-USR1', str(pid)])
Jeffrey Yasskincf26f542008-03-21 05:02:44 +0000109 # This wait should be interrupted by the signal's exception.
110 self.wait(child)
Jeffrey Yasskinab561312008-04-02 04:07:44 +0000111 time.sleep(1) # Give the signal time to be delivered.
Jeffrey Yasskincf26f542008-03-21 05:02:44 +0000112 self.fail('HandlerBCalled exception not thrown')
113 except HandlerBCalled:
Jeffrey Yasskincf26f542008-03-21 05:02:44 +0000114 self.assertTrue(self.b_called)
115 self.assertFalse(self.a_called)
Georg Brandl9f2b93e2007-08-24 18:07:52 +0000116 if test_support.verbose:
Jeffrey Yasskincf26f542008-03-21 05:02:44 +0000117 print "HandlerBCalled exception caught"
Neal Norwitzec3c5e32006-07-30 19:18:38 +0000118
Jeffrey Yasskinab561312008-04-02 04:07:44 +0000119 child = ignoring_eintr(subprocess.Popen, ['kill', '-USR2', str(pid)])
120 if child:
121 self.wait(child) # Nothing should happen.
Jeffrey Yasskincf26f542008-03-21 05:02:44 +0000122
123 try:
124 signal.alarm(1)
125 # The race condition in pause doesn't matter in this case,
126 # since alarm is going to raise a KeyboardException, which
127 # will skip the call.
128 signal.pause()
Jeffrey Yasskinab561312008-04-02 04:07:44 +0000129 # But if another signal arrives before the alarm, pause
130 # may return early.
131 time.sleep(1)
Georg Brandl9f2b93e2007-08-24 18:07:52 +0000132 except KeyboardInterrupt:
133 if test_support.verbose:
134 print "KeyboardInterrupt (the alarm() went off)"
Georg Brandl9f2b93e2007-08-24 18:07:52 +0000135 except:
Jeffrey Yasskinab561312008-04-02 04:07:44 +0000136 self.fail("Some other exception woke us from pause: %s" %
Jeffrey Yasskincf26f542008-03-21 05:02:44 +0000137 traceback.format_exc())
138 else:
Jeffrey Yasskinab561312008-04-02 04:07:44 +0000139 self.fail("pause returned of its own accord, and the signal"
140 " didn't arrive after another second.")
Georg Brandl9f2b93e2007-08-24 18:07:52 +0000141
Jeffrey Yasskincf26f542008-03-21 05:02:44 +0000142 def test_main(self):
R. David Murray12c5fbb2010-04-21 01:41:41 +0000143 # Issue 3864, unknown if this affects earlier versions of freebsd also
144 if sys.platform=='freebsd6' and test_support.verbose:
145 sys.stderr.write('skipping -- inter process signals not reliable '
146 '(do not mix well with threading) on freebsd6\n')
147 return
Jeffrey Yasskincf26f542008-03-21 05:02:44 +0000148 # This function spawns a child process to insulate the main
149 # test-running process from all the signals. It then
150 # communicates with that child process over a pipe and
151 # re-raises information about any exceptions the child
152 # throws. The real work happens in self.run_test().
153 os_done_r, os_done_w = os.pipe()
154 with nested(closing(os.fdopen(os_done_r)),
155 closing(os.fdopen(os_done_w, 'w'))) as (done_r, done_w):
156 child = os.fork()
157 if child == 0:
158 # In the child process; run the test and report results
159 # through the pipe.
160 try:
161 done_r.close()
162 # Have to close done_w again here because
163 # exit_subprocess() will skip the enclosing with block.
164 with closing(done_w):
165 try:
166 self.run_test()
167 except:
168 pickle.dump(traceback.format_exc(), done_w)
169 else:
170 pickle.dump(None, done_w)
171 except:
172 print 'Uh oh, raised from pickle.'
173 traceback.print_exc()
174 finally:
175 exit_subprocess()
176
177 done_w.close()
178 # Block for up to MAX_DURATION seconds for the test to finish.
179 r, w, x = select.select([done_r], [], [], self.MAX_DURATION)
180 if done_r in r:
181 tb = pickle.load(done_r)
182 if tb:
183 self.fail(tb)
184 else:
185 os.kill(child, signal.SIGKILL)
186 self.fail('Test deadlocked after %d seconds.' %
187 self.MAX_DURATION)
Georg Brandl9f2b93e2007-08-24 18:07:52 +0000188
189
190class BasicSignalTests(unittest.TestCase):
Jeffrey Yasskincf26f542008-03-21 05:02:44 +0000191 def trivial_signal_handler(self, *args):
192 pass
193
Georg Brandl9f2b93e2007-08-24 18:07:52 +0000194 def test_out_of_range_signal_number_raises_error(self):
195 self.assertRaises(ValueError, signal.getsignal, 4242)
196
Georg Brandl9f2b93e2007-08-24 18:07:52 +0000197 self.assertRaises(ValueError, signal.signal, 4242,
Jeffrey Yasskincf26f542008-03-21 05:02:44 +0000198 self.trivial_signal_handler)
Georg Brandl9f2b93e2007-08-24 18:07:52 +0000199
200 def test_setting_signal_handler_to_none_raises_error(self):
201 self.assertRaises(TypeError, signal.signal,
202 signal.SIGUSR1, None)
203
Jeffrey Yasskincf26f542008-03-21 05:02:44 +0000204 def test_getsignal(self):
205 hup = signal.signal(signal.SIGHUP, self.trivial_signal_handler)
206 self.assertEquals(signal.getsignal(signal.SIGHUP),
207 self.trivial_signal_handler)
208 signal.signal(signal.SIGHUP, hup)
209 self.assertEquals(signal.getsignal(signal.SIGHUP), hup)
210
211
Guido van Rossum02de8972007-12-19 19:41:06 +0000212class WakeupSignalTests(unittest.TestCase):
213 TIMEOUT_FULL = 10
214 TIMEOUT_HALF = 5
215
216 def test_wakeup_fd_early(self):
217 import select
218
219 signal.alarm(1)
220 before_time = time.time()
221 # We attempt to get a signal during the sleep,
222 # before select is called
223 time.sleep(self.TIMEOUT_FULL)
224 mid_time = time.time()
225 self.assert_(mid_time - before_time < self.TIMEOUT_HALF)
226 select.select([self.read], [], [], self.TIMEOUT_FULL)
227 after_time = time.time()
228 self.assert_(after_time - mid_time < self.TIMEOUT_HALF)
229
230 def test_wakeup_fd_during(self):
231 import select
232
233 signal.alarm(1)
234 before_time = time.time()
235 # We attempt to get a signal during the select call
236 self.assertRaises(select.error, select.select,
237 [self.read], [], [], self.TIMEOUT_FULL)
238 after_time = time.time()
239 self.assert_(after_time - before_time < self.TIMEOUT_HALF)
240
241 def setUp(self):
242 import fcntl
243
244 self.alrm = signal.signal(signal.SIGALRM, lambda x,y:None)
245 self.read, self.write = os.pipe()
246 flags = fcntl.fcntl(self.write, fcntl.F_GETFL, 0)
247 flags = flags | os.O_NONBLOCK
248 fcntl.fcntl(self.write, fcntl.F_SETFL, flags)
249 self.old_wakeup = signal.set_wakeup_fd(self.write)
250
251 def tearDown(self):
252 signal.set_wakeup_fd(self.old_wakeup)
253 os.close(self.read)
254 os.close(self.write)
255 signal.signal(signal.SIGALRM, self.alrm)
256
Facundo Batista7e251e82008-02-23 15:07:35 +0000257class SiginterruptTest(unittest.TestCase):
258 signum = signal.SIGUSR1
259 def readpipe_interrupted(self, cb):
260 r, w = os.pipe()
261 ppid = os.getpid()
262 pid = os.fork()
263
264 oldhandler = signal.signal(self.signum, lambda x,y: None)
265 cb()
266 if pid==0:
267 # child code: sleep, kill, sleep. and then exit,
268 # which closes the pipe from which the parent process reads
269 try:
270 time.sleep(0.2)
271 os.kill(ppid, self.signum)
272 time.sleep(0.2)
273 finally:
Jeffrey Yasskincf26f542008-03-21 05:02:44 +0000274 exit_subprocess()
Facundo Batista7e251e82008-02-23 15:07:35 +0000275
276 try:
277 os.close(w)
278
279 try:
280 d=os.read(r, 1)
281 return False
282 except OSError, err:
283 if err.errno != errno.EINTR:
284 raise
285 return True
286 finally:
287 signal.signal(self.signum, oldhandler)
288 os.waitpid(pid, 0)
289
290 def test_without_siginterrupt(self):
291 i=self.readpipe_interrupted(lambda: None)
292 self.assertEquals(i, True)
293
294 def test_siginterrupt_on(self):
295 i=self.readpipe_interrupted(lambda: signal.siginterrupt(self.signum, 1))
296 self.assertEquals(i, True)
297
298 def test_siginterrupt_off(self):
299 i=self.readpipe_interrupted(lambda: signal.siginterrupt(self.signum, 0))
300 self.assertEquals(i, False)
Guido van Rossum02de8972007-12-19 19:41:06 +0000301
Martin v. Löwisaef18b12008-03-24 13:31:16 +0000302class ItimerTest(unittest.TestCase):
303 def setUp(self):
304 self.hndl_called = False
305 self.hndl_count = 0
306 self.itimer = None
Neal Norwitzbb89e682008-03-25 07:00:39 +0000307 self.old_alarm = signal.signal(signal.SIGALRM, self.sig_alrm)
Martin v. Löwisaef18b12008-03-24 13:31:16 +0000308
309 def tearDown(self):
Neal Norwitzbb89e682008-03-25 07:00:39 +0000310 signal.signal(signal.SIGALRM, self.old_alarm)
Martin v. Löwisaef18b12008-03-24 13:31:16 +0000311 if self.itimer is not None: # test_itimer_exc doesn't change this attr
312 # just ensure that itimer is stopped
313 signal.setitimer(self.itimer, 0)
314
315 def sig_alrm(self, *args):
316 self.hndl_called = True
317 if test_support.verbose:
318 print("SIGALRM handler invoked", args)
319
320 def sig_vtalrm(self, *args):
321 self.hndl_called = True
322
323 if self.hndl_count > 3:
324 # it shouldn't be here, because it should have been disabled.
325 raise signal.ItimerError("setitimer didn't disable ITIMER_VIRTUAL "
326 "timer.")
327 elif self.hndl_count == 3:
328 # disable ITIMER_VIRTUAL, this function shouldn't be called anymore
329 signal.setitimer(signal.ITIMER_VIRTUAL, 0)
330 if test_support.verbose:
331 print("last SIGVTALRM handler call")
332
333 self.hndl_count += 1
334
335 if test_support.verbose:
336 print("SIGVTALRM handler invoked", args)
337
338 def sig_prof(self, *args):
339 self.hndl_called = True
340 signal.setitimer(signal.ITIMER_PROF, 0)
341
342 if test_support.verbose:
343 print("SIGPROF handler invoked", args)
344
345 def test_itimer_exc(self):
346 # XXX I'm assuming -1 is an invalid itimer, but maybe some platform
347 # defines it ?
348 self.assertRaises(signal.ItimerError, signal.setitimer, -1, 0)
Neal Norwitzbb89e682008-03-25 07:00:39 +0000349 # Negative times are treated as zero on some platforms.
350 if 0:
351 self.assertRaises(signal.ItimerError,
352 signal.setitimer, signal.ITIMER_REAL, -1)
Martin v. Löwisaef18b12008-03-24 13:31:16 +0000353
354 def test_itimer_real(self):
355 self.itimer = signal.ITIMER_REAL
Martin v. Löwisaef18b12008-03-24 13:31:16 +0000356 signal.setitimer(self.itimer, 1.0)
357 if test_support.verbose:
358 print("\ncall pause()...")
359 signal.pause()
360
361 self.assertEqual(self.hndl_called, True)
362
363 def test_itimer_virtual(self):
R. David Murray12c5fbb2010-04-21 01:41:41 +0000364 # Issue 3864, unknown if this affects earlier versions of freebsd also
365 if sys.platform=='freebsd6' and test_support.verbose:
366 sys.stderr.write('skipping -- itimer not reliable '
367 '(does not mix well with threading) on freebsd6\n')
368 return
Martin v. Löwisaef18b12008-03-24 13:31:16 +0000369 self.itimer = signal.ITIMER_VIRTUAL
370 signal.signal(signal.SIGVTALRM, self.sig_vtalrm)
371 signal.setitimer(self.itimer, 0.3, 0.2)
372
Mark Dickinson265035e2009-10-31 10:37:15 +0000373 start_time = time.time()
Stefan Krah488fea32010-04-20 08:07:08 +0000374 while time.time() - start_time < 60.0:
Mark Dickinson5fab1692009-10-04 18:41:25 +0000375 # use up some virtual time by doing real work
376 _ = pow(12345, 67890, 10000019)
Martin v. Löwisaef18b12008-03-24 13:31:16 +0000377 if signal.getitimer(self.itimer) == (0.0, 0.0):
378 break # sig_vtalrm handler stopped this itimer
Stefan Krah488fea32010-04-20 08:07:08 +0000379 else: # Issue 8424
380 sys.stdout.write("test_itimer_virtual: timeout: likely cause: "
381 "machine too slow or load too high.\n")
382 return
Martin v. Löwisaef18b12008-03-24 13:31:16 +0000383
384 # virtual itimer should be (0.0, 0.0) now
385 self.assertEquals(signal.getitimer(self.itimer), (0.0, 0.0))
386 # and the handler should have been called
387 self.assertEquals(self.hndl_called, True)
388
389 def test_itimer_prof(self):
R. David Murray12c5fbb2010-04-21 01:41:41 +0000390 # Issue 3864, unknown if this affects earlier versions of freebsd also
391 if sys.platform=='freebsd6' and test_support.verbose:
392 sys.stderr.write('skipping -- itimer not reliable '
393 '(does not mix well with threading) on freebsd6\n')
394 return
Martin v. Löwisaef18b12008-03-24 13:31:16 +0000395 self.itimer = signal.ITIMER_PROF
396 signal.signal(signal.SIGPROF, self.sig_prof)
Jeffrey Yasskin2b860db2008-04-04 04:51:19 +0000397 signal.setitimer(self.itimer, 0.2, 0.2)
Martin v. Löwisaef18b12008-03-24 13:31:16 +0000398
Mark Dickinson265035e2009-10-31 10:37:15 +0000399 start_time = time.time()
Stefan Krah488fea32010-04-20 08:07:08 +0000400 while time.time() - start_time < 60.0:
Mark Dickinson265035e2009-10-31 10:37:15 +0000401 # do some work
402 _ = pow(12345, 67890, 10000019)
Martin v. Löwisaef18b12008-03-24 13:31:16 +0000403 if signal.getitimer(self.itimer) == (0.0, 0.0):
404 break # sig_prof handler stopped this itimer
Stefan Krah488fea32010-04-20 08:07:08 +0000405 else: # Issue 8424
406 sys.stdout.write("test_itimer_prof: timeout: likely cause: "
407 "machine too slow or load too high.\n")
408 return
Martin v. Löwisaef18b12008-03-24 13:31:16 +0000409
Jeffrey Yasskin2b860db2008-04-04 04:51:19 +0000410 # profiling itimer should be (0.0, 0.0) now
411 self.assertEquals(signal.getitimer(self.itimer), (0.0, 0.0))
412 # and the handler should have been called
Martin v. Löwisaef18b12008-03-24 13:31:16 +0000413 self.assertEqual(self.hndl_called, True)
414
Georg Brandl9f2b93e2007-08-24 18:07:52 +0000415def test_main():
Guido van Rossum02de8972007-12-19 19:41:06 +0000416 test_support.run_unittest(BasicSignalTests, InterProcessSignalTests,
Martin v. Löwisaef18b12008-03-24 13:31:16 +0000417 WakeupSignalTests, SiginterruptTest, ItimerTest)
Georg Brandl9f2b93e2007-08-24 18:07:52 +0000418
419
420if __name__ == "__main__":
421 test_main()