/Lib/test/test_signal.py

http://unladen-swallow.googlecode.com/ · Python · 401 lines · 284 code · 68 blank · 49 comment · 55 complexity · 0bc8131bad910979bdc1a5d879ef95e1 MD5 · raw file

  1. import unittest
  2. from test import test_support
  3. from contextlib import closing, nested
  4. import gc
  5. import pickle
  6. import select
  7. import signal
  8. import subprocess
  9. import traceback
  10. import sys, os, time, errno
  11. if sys.platform[:3] in ('win', 'os2') or sys.platform == 'riscos':
  12. raise test_support.TestSkipped("Can't test signal on %s" % \
  13. sys.platform)
  14. class HandlerBCalled(Exception):
  15. pass
  16. def exit_subprocess():
  17. """Use os._exit(0) to exit the current subprocess.
  18. Otherwise, the test catches the SystemExit and continues executing
  19. in parallel with the original test, so you wind up with an
  20. exponential number of tests running concurrently.
  21. """
  22. os._exit(0)
  23. def ignoring_eintr(__func, *args, **kwargs):
  24. try:
  25. return __func(*args, **kwargs)
  26. except EnvironmentError as e:
  27. if e.errno != errno.EINTR:
  28. raise
  29. return None
  30. class InterProcessSignalTests(unittest.TestCase):
  31. MAX_DURATION = 20 # Entire test should last at most 20 sec.
  32. def setUp(self):
  33. self.using_gc = gc.isenabled()
  34. gc.disable()
  35. def tearDown(self):
  36. if self.using_gc:
  37. gc.enable()
  38. def format_frame(self, frame, limit=None):
  39. return ''.join(traceback.format_stack(frame, limit=limit))
  40. def handlerA(self, signum, frame):
  41. self.a_called = True
  42. if test_support.verbose:
  43. print "handlerA invoked from signal %s at:\n%s" % (
  44. signum, self.format_frame(frame, limit=1))
  45. def handlerB(self, signum, frame):
  46. self.b_called = True
  47. if test_support.verbose:
  48. print "handlerB invoked from signal %s at:\n%s" % (
  49. signum, self.format_frame(frame, limit=1))
  50. raise HandlerBCalled(signum, self.format_frame(frame))
  51. def wait(self, child):
  52. """Wait for child to finish, ignoring EINTR."""
  53. while True:
  54. try:
  55. child.wait()
  56. return
  57. except OSError as e:
  58. if e.errno != errno.EINTR:
  59. raise
  60. def run_test(self):
  61. # Install handlers. This function runs in a sub-process, so we
  62. # don't worry about re-setting the default handlers.
  63. signal.signal(signal.SIGHUP, self.handlerA)
  64. signal.signal(signal.SIGUSR1, self.handlerB)
  65. signal.signal(signal.SIGUSR2, signal.SIG_IGN)
  66. signal.signal(signal.SIGALRM, signal.default_int_handler)
  67. # Variables the signals will modify:
  68. self.a_called = False
  69. self.b_called = False
  70. # Let the sub-processes know who to send signals to.
  71. pid = os.getpid()
  72. if test_support.verbose:
  73. print "test runner's pid is", pid
  74. child = ignoring_eintr(subprocess.Popen, ['kill', '-HUP', str(pid)])
  75. if child:
  76. self.wait(child)
  77. if not self.a_called:
  78. time.sleep(1) # Give the signal time to be delivered.
  79. self.assertTrue(self.a_called)
  80. self.assertFalse(self.b_called)
  81. self.a_called = False
  82. # Make sure the signal isn't delivered while the previous
  83. # Popen object is being destroyed, because __del__ swallows
  84. # exceptions.
  85. del child
  86. try:
  87. child = subprocess.Popen(['kill', '-USR1', str(pid)])
  88. # This wait should be interrupted by the signal's exception.
  89. self.wait(child)
  90. time.sleep(1) # Give the signal time to be delivered.
  91. self.fail('HandlerBCalled exception not thrown')
  92. except HandlerBCalled:
  93. self.assertTrue(self.b_called)
  94. self.assertFalse(self.a_called)
  95. if test_support.verbose:
  96. print "HandlerBCalled exception caught"
  97. child = ignoring_eintr(subprocess.Popen, ['kill', '-USR2', str(pid)])
  98. if child:
  99. self.wait(child) # Nothing should happen.
  100. try:
  101. signal.alarm(1)
  102. # The race condition in pause doesn't matter in this case,
  103. # since alarm is going to raise a KeyboardException, which
  104. # will skip the call.
  105. signal.pause()
  106. # But if another signal arrives before the alarm, pause
  107. # may return early.
  108. time.sleep(1)
  109. except KeyboardInterrupt:
  110. if test_support.verbose:
  111. print "KeyboardInterrupt (the alarm() went off)"
  112. except:
  113. self.fail("Some other exception woke us from pause: %s" %
  114. traceback.format_exc())
  115. else:
  116. self.fail("pause returned of its own accord, and the signal"
  117. " didn't arrive after another second.")
  118. def test_main(self):
  119. # Call several functions once so that -Xjit=always will convert
  120. # them to machine code eagerly. Otherwise they get JITted
  121. # during the select() call and make the test time out.
  122. self.assertTrue(True)
  123. self.assertFalse(False)
  124. self.wait(ignoring_eintr(subprocess.Popen, ['true']))
  125. # This function spawns a child process to insulate the main
  126. # test-running process from all the signals. It then
  127. # communicates with that child process over a pipe and
  128. # re-raises information about any exceptions the child
  129. # throws. The real work happens in self.run_test().
  130. os_done_r, os_done_w = os.pipe()
  131. with nested(closing(os.fdopen(os_done_r)),
  132. closing(os.fdopen(os_done_w, 'w'))) as (done_r, done_w):
  133. child = os.fork()
  134. if child == 0:
  135. # In the child process; run the test and report results
  136. # through the pipe.
  137. try:
  138. done_r.close()
  139. # Have to close done_w again here because
  140. # exit_subprocess() will skip the enclosing with block.
  141. with closing(done_w):
  142. try:
  143. self.run_test()
  144. except:
  145. pickle.dump(traceback.format_exc(), done_w)
  146. else:
  147. pickle.dump(None, done_w)
  148. except:
  149. print 'Uh oh, raised from pickle.'
  150. traceback.print_exc()
  151. finally:
  152. exit_subprocess()
  153. done_w.close()
  154. # Block for up to MAX_DURATION seconds for the test to finish.
  155. r, w, x = select.select([done_r], [], [], self.MAX_DURATION)
  156. if done_r in r:
  157. tb = pickle.load(done_r)
  158. if tb:
  159. self.fail(tb)
  160. else:
  161. os.kill(child, signal.SIGKILL)
  162. self.fail('Test deadlocked after %d seconds.' %
  163. self.MAX_DURATION)
  164. class BasicSignalTests(unittest.TestCase):
  165. def trivial_signal_handler(self, *args):
  166. pass
  167. def test_out_of_range_signal_number_raises_error(self):
  168. self.assertRaises(ValueError, signal.getsignal, 4242)
  169. self.assertRaises(ValueError, signal.signal, 4242,
  170. self.trivial_signal_handler)
  171. def test_setting_signal_handler_to_none_raises_error(self):
  172. self.assertRaises(TypeError, signal.signal,
  173. signal.SIGUSR1, None)
  174. def test_getsignal(self):
  175. hup = signal.signal(signal.SIGHUP, self.trivial_signal_handler)
  176. self.assertEquals(signal.getsignal(signal.SIGHUP),
  177. self.trivial_signal_handler)
  178. signal.signal(signal.SIGHUP, hup)
  179. self.assertEquals(signal.getsignal(signal.SIGHUP), hup)
  180. class WakeupSignalTests(unittest.TestCase):
  181. TIMEOUT_FULL = 10
  182. TIMEOUT_HALF = 5
  183. def test_wakeup_fd_early(self):
  184. import select
  185. signal.alarm(1)
  186. before_time = time.time()
  187. # We attempt to get a signal during the sleep,
  188. # before select is called
  189. time.sleep(self.TIMEOUT_FULL)
  190. mid_time = time.time()
  191. self.assert_(mid_time - before_time < self.TIMEOUT_HALF)
  192. select.select([self.read], [], [], self.TIMEOUT_FULL)
  193. after_time = time.time()
  194. self.assert_(after_time - mid_time < self.TIMEOUT_HALF)
  195. def test_wakeup_fd_during(self):
  196. import select
  197. signal.alarm(1)
  198. before_time = time.time()
  199. # We attempt to get a signal during the select call
  200. self.assertRaises(select.error, select.select,
  201. [self.read], [], [], self.TIMEOUT_FULL)
  202. after_time = time.time()
  203. self.assert_(after_time - before_time < self.TIMEOUT_HALF)
  204. def setUp(self):
  205. import fcntl
  206. self.alrm = signal.signal(signal.SIGALRM, lambda x,y:None)
  207. self.read, self.write = os.pipe()
  208. flags = fcntl.fcntl(self.write, fcntl.F_GETFL, 0)
  209. flags = flags | os.O_NONBLOCK
  210. fcntl.fcntl(self.write, fcntl.F_SETFL, flags)
  211. self.old_wakeup = signal.set_wakeup_fd(self.write)
  212. def tearDown(self):
  213. signal.set_wakeup_fd(self.old_wakeup)
  214. os.close(self.read)
  215. os.close(self.write)
  216. signal.signal(signal.SIGALRM, self.alrm)
  217. class SiginterruptTest(unittest.TestCase):
  218. signum = signal.SIGUSR1
  219. def readpipe_interrupted(self, cb):
  220. r, w = os.pipe()
  221. ppid = os.getpid()
  222. pid = os.fork()
  223. oldhandler = signal.signal(self.signum, lambda x,y: None)
  224. cb()
  225. if pid==0:
  226. # child code: sleep, kill, sleep. and then exit,
  227. # which closes the pipe from which the parent process reads
  228. try:
  229. time.sleep(0.2)
  230. os.kill(ppid, self.signum)
  231. time.sleep(0.2)
  232. finally:
  233. exit_subprocess()
  234. try:
  235. os.close(w)
  236. try:
  237. d=os.read(r, 1)
  238. return False
  239. except OSError, err:
  240. if err.errno != errno.EINTR:
  241. raise
  242. return True
  243. finally:
  244. signal.signal(self.signum, oldhandler)
  245. os.waitpid(pid, 0)
  246. def test_without_siginterrupt(self):
  247. i=self.readpipe_interrupted(lambda: None)
  248. self.assertEquals(i, True)
  249. def test_siginterrupt_on(self):
  250. i=self.readpipe_interrupted(lambda: signal.siginterrupt(self.signum, 1))
  251. self.assertEquals(i, True)
  252. def test_siginterrupt_off(self):
  253. i=self.readpipe_interrupted(lambda: signal.siginterrupt(self.signum, 0))
  254. self.assertEquals(i, False)
  255. class ItimerTest(unittest.TestCase):
  256. def setUp(self):
  257. self.hndl_called = False
  258. self.hndl_count = 0
  259. self.itimer = None
  260. self.old_alarm = signal.signal(signal.SIGALRM, self.sig_alrm)
  261. def tearDown(self):
  262. signal.signal(signal.SIGALRM, self.old_alarm)
  263. if self.itimer is not None: # test_itimer_exc doesn't change this attr
  264. # just ensure that itimer is stopped
  265. signal.setitimer(self.itimer, 0)
  266. def sig_alrm(self, *args):
  267. self.hndl_called = True
  268. if test_support.verbose:
  269. print("SIGALRM handler invoked", args)
  270. def sig_vtalrm(self, *args):
  271. self.hndl_called = True
  272. if self.hndl_count > 3:
  273. # it shouldn't be here, because it should have been disabled.
  274. raise signal.ItimerError("setitimer didn't disable ITIMER_VIRTUAL "
  275. "timer.")
  276. elif self.hndl_count == 3:
  277. # disable ITIMER_VIRTUAL, this function shouldn't be called anymore
  278. signal.setitimer(signal.ITIMER_VIRTUAL, 0)
  279. if test_support.verbose:
  280. print("last SIGVTALRM handler call")
  281. self.hndl_count += 1
  282. if test_support.verbose:
  283. print("SIGVTALRM handler invoked", args)
  284. def sig_prof(self, *args):
  285. self.hndl_called = True
  286. signal.setitimer(signal.ITIMER_PROF, 0)
  287. if test_support.verbose:
  288. print("SIGPROF handler invoked", args)
  289. def test_itimer_exc(self):
  290. # XXX I'm assuming -1 is an invalid itimer, but maybe some platform
  291. # defines it ?
  292. self.assertRaises(signal.ItimerError, signal.setitimer, -1, 0)
  293. # Negative times are treated as zero on some platforms.
  294. if 0:
  295. self.assertRaises(signal.ItimerError,
  296. signal.setitimer, signal.ITIMER_REAL, -1)
  297. def test_itimer_real(self):
  298. self.itimer = signal.ITIMER_REAL
  299. signal.setitimer(self.itimer, 1.0)
  300. if test_support.verbose:
  301. print("\ncall pause()...")
  302. signal.pause()
  303. self.assertEqual(self.hndl_called, True)
  304. def test_itimer_virtual(self):
  305. self.itimer = signal.ITIMER_VIRTUAL
  306. signal.signal(signal.SIGVTALRM, self.sig_vtalrm)
  307. signal.setitimer(self.itimer, 0.3, 0.2)
  308. for i in xrange(100000000):
  309. # use up some virtual time by doing real work
  310. _ = pow(12345, 67890, 10000019)
  311. if signal.getitimer(self.itimer) == (0.0, 0.0):
  312. break # sig_vtalrm handler stopped this itimer
  313. # virtual itimer should be (0.0, 0.0) now
  314. self.assertEquals(signal.getitimer(self.itimer), (0.0, 0.0))
  315. # and the handler should have been called
  316. self.assertEquals(self.hndl_called, True)
  317. def test_itimer_prof(self):
  318. self.itimer = signal.ITIMER_PROF
  319. signal.signal(signal.SIGPROF, self.sig_prof)
  320. signal.setitimer(self.itimer, 0.2, 0.2)
  321. for i in xrange(100000000):
  322. if signal.getitimer(self.itimer) == (0.0, 0.0):
  323. break # sig_prof handler stopped this itimer
  324. # profiling itimer should be (0.0, 0.0) now
  325. self.assertEquals(signal.getitimer(self.itimer), (0.0, 0.0))
  326. # and the handler should have been called
  327. self.assertEqual(self.hndl_called, True)
  328. def test_main():
  329. test_support.run_unittest(BasicSignalTests, InterProcessSignalTests,
  330. WakeupSignalTests, SiginterruptTest, ItimerTest)
  331. if __name__ == "__main__":
  332. test_main()