/Lib/test/test_pty.py

http://unladen-swallow.googlecode.com/ · Python · 196 lines · 113 code · 29 blank · 54 comment · 25 complexity · 6d7589d6093053dc4f1d60cb35257eff MD5 · raw file

  1. import errno
  2. import fcntl
  3. import pty
  4. import os
  5. import sys
  6. import signal
  7. from test.test_support import verbose, TestSkipped, run_unittest
  8. import unittest
  9. TEST_STRING_1 = "I wish to buy a fish license.\n"
  10. TEST_STRING_2 = "For my pet fish, Eric.\n"
  11. if verbose:
  12. def debug(msg):
  13. print msg
  14. else:
  15. def debug(msg):
  16. pass
  17. def normalize_output(data):
  18. # Some operating systems do conversions on newline. We could possibly
  19. # fix that by doing the appropriate termios.tcsetattr()s. I couldn't
  20. # figure out the right combo on Tru64 and I don't have an IRIX box.
  21. # So just normalize the output and doc the problem O/Ses by allowing
  22. # certain combinations for some platforms, but avoid allowing other
  23. # differences (like extra whitespace, trailing garbage, etc.)
  24. # This is about the best we can do without getting some feedback
  25. # from someone more knowledgable.
  26. # OSF/1 (Tru64) apparently turns \n into \r\r\n.
  27. if data.endswith('\r\r\n'):
  28. return data.replace('\r\r\n', '\n')
  29. # IRIX apparently turns \n into \r\n.
  30. if data.endswith('\r\n'):
  31. return data.replace('\r\n', '\n')
  32. return data
  33. # Marginal testing of pty suite. Cannot do extensive 'do or fail' testing
  34. # because pty code is not too portable.
  35. # XXX(nnorwitz): these tests leak fds when there is an error.
  36. class PtyTest(unittest.TestCase):
  37. def setUp(self):
  38. # isatty() and close() can hang on some platforms. Set an alarm
  39. # before running the test to make sure we don't hang forever.
  40. self.old_alarm = signal.signal(signal.SIGALRM, self.handle_sig)
  41. signal.alarm(10)
  42. def tearDown(self):
  43. # remove alarm, restore old alarm handler
  44. signal.alarm(0)
  45. signal.signal(signal.SIGALRM, self.old_alarm)
  46. def handle_sig(self, sig, frame):
  47. self.fail("isatty hung")
  48. def test_basic(self):
  49. try:
  50. debug("Calling master_open()")
  51. master_fd, slave_name = pty.master_open()
  52. debug("Got master_fd '%d', slave_name '%s'" %
  53. (master_fd, slave_name))
  54. debug("Calling slave_open(%r)" % (slave_name,))
  55. slave_fd = pty.slave_open(slave_name)
  56. debug("Got slave_fd '%d'" % slave_fd)
  57. except OSError:
  58. # " An optional feature could not be imported " ... ?
  59. raise TestSkipped, "Pseudo-terminals (seemingly) not functional."
  60. self.assertTrue(os.isatty(slave_fd), 'slave_fd is not a tty')
  61. # Solaris requires reading the fd before anything is returned.
  62. # My guess is that since we open and close the slave fd
  63. # in master_open(), we need to read the EOF.
  64. # Ensure the fd is non-blocking in case there's nothing to read.
  65. orig_flags = fcntl.fcntl(master_fd, fcntl.F_GETFL)
  66. fcntl.fcntl(master_fd, fcntl.F_SETFL, orig_flags | os.O_NONBLOCK)
  67. try:
  68. s1 = os.read(master_fd, 1024)
  69. self.assertEquals('', s1)
  70. except OSError, e:
  71. if e.errno != errno.EAGAIN:
  72. raise
  73. # Restore the original flags.
  74. fcntl.fcntl(master_fd, fcntl.F_SETFL, orig_flags)
  75. debug("Writing to slave_fd")
  76. os.write(slave_fd, TEST_STRING_1)
  77. s1 = os.read(master_fd, 1024)
  78. self.assertEquals('I wish to buy a fish license.\n',
  79. normalize_output(s1))
  80. debug("Writing chunked output")
  81. os.write(slave_fd, TEST_STRING_2[:5])
  82. os.write(slave_fd, TEST_STRING_2[5:])
  83. s2 = os.read(master_fd, 1024)
  84. self.assertEquals('For my pet fish, Eric.\n', normalize_output(s2))
  85. os.close(slave_fd)
  86. os.close(master_fd)
  87. def test_fork(self):
  88. debug("calling pty.fork()")
  89. pid, master_fd = pty.fork()
  90. if pid == pty.CHILD:
  91. # stdout should be connected to a tty.
  92. if not os.isatty(1):
  93. debug("Child's fd 1 is not a tty?!")
  94. os._exit(3)
  95. # After pty.fork(), the child should already be a session leader.
  96. # (on those systems that have that concept.)
  97. debug("In child, calling os.setsid()")
  98. try:
  99. os.setsid()
  100. except OSError:
  101. # Good, we already were session leader
  102. debug("Good: OSError was raised.")
  103. pass
  104. except AttributeError:
  105. # Have pty, but not setsid()?
  106. debug("No setsid() available?")
  107. pass
  108. except:
  109. # We don't want this error to propagate, escaping the call to
  110. # os._exit() and causing very peculiar behavior in the calling
  111. # regrtest.py !
  112. # Note: could add traceback printing here.
  113. debug("An unexpected error was raised.")
  114. os._exit(1)
  115. else:
  116. debug("os.setsid() succeeded! (bad!)")
  117. os._exit(2)
  118. os._exit(4)
  119. else:
  120. debug("Waiting for child (%d) to finish." % pid)
  121. # In verbose mode, we have to consume the debug output from the
  122. # child or the child will block, causing this test to hang in the
  123. # parent's waitpid() call. The child blocks after a
  124. # platform-dependent amount of data is written to its fd. On
  125. # Linux 2.6, it's 4000 bytes and the child won't block, but on OS
  126. # X even the small writes in the child above will block it. Also
  127. # on Linux, the read() will throw an OSError (input/output error)
  128. # when it tries to read past the end of the buffer but the child's
  129. # already exited, so catch and discard those exceptions. It's not
  130. # worth checking for EIO.
  131. while True:
  132. try:
  133. data = os.read(master_fd, 80)
  134. except OSError:
  135. break
  136. if not data:
  137. break
  138. sys.stdout.write(data.replace('\r\n', '\n'))
  139. ##line = os.read(master_fd, 80)
  140. ##lines = line.replace('\r\n', '\n').split('\n')
  141. ##if False and lines != ['In child, calling os.setsid()',
  142. ## 'Good: OSError was raised.', '']:
  143. ## raise TestFailed("Unexpected output from child: %r" % line)
  144. (pid, status) = os.waitpid(pid, 0)
  145. res = status >> 8
  146. debug("Child (%d) exited with status %d (%d)." % (pid, res, status))
  147. if res == 1:
  148. self.fail("Child raised an unexpected exception in os.setsid()")
  149. elif res == 2:
  150. self.fail("pty.fork() failed to make child a session leader.")
  151. elif res == 3:
  152. self.fail("Child spawned by pty.fork() did not have a tty as stdout")
  153. elif res != 4:
  154. self.fail("pty.fork() failed for unknown reasons.")
  155. ##debug("Reading from master_fd now that the child has exited")
  156. ##try:
  157. ## s1 = os.read(master_fd, 1024)
  158. ##except os.error:
  159. ## pass
  160. ##else:
  161. ## raise TestFailed("Read from master_fd did not raise exception")
  162. os.close(master_fd)
  163. # pty.fork() passed.
  164. def test_main(verbose=None):
  165. run_unittest(PtyTest)
  166. if __name__ == "__main__":
  167. test_main()