PageRenderTime 68ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/contrib/python-x86_64/lib/python2.7/test/test_pty.py

https://gitlab.com/atom-k/android-plus-plus
Python | 289 lines | 249 code | 18 blank | 22 comment | 10 complexity | d01cd727378485d84e02f88095082e26 MD5 | raw file
  1. from test.test_support import verbose, run_unittest, import_module
  2. #Skip these tests if either fcntl or termios is not available
  3. fcntl = import_module('fcntl')
  4. import_module('termios')
  5. import errno
  6. import pty
  7. import os
  8. import sys
  9. import select
  10. import signal
  11. import socket
  12. import unittest
  13. TEST_STRING_1 = "I wish to buy a fish license.\n"
  14. TEST_STRING_2 = "For my pet fish, Eric.\n"
  15. if verbose:
  16. def debug(msg):
  17. print msg
  18. else:
  19. def debug(msg):
  20. pass
  21. def normalize_output(data):
  22. # Some operating systems do conversions on newline. We could possibly
  23. # fix that by doing the appropriate termios.tcsetattr()s. I couldn't
  24. # figure out the right combo on Tru64 and I don't have an IRIX box.
  25. # So just normalize the output and doc the problem O/Ses by allowing
  26. # certain combinations for some platforms, but avoid allowing other
  27. # differences (like extra whitespace, trailing garbage, etc.)
  28. # This is about the best we can do without getting some feedback
  29. # from someone more knowledgable.
  30. # OSF/1 (Tru64) apparently turns \n into \r\r\n.
  31. if data.endswith('\r\r\n'):
  32. return data.replace('\r\r\n', '\n')
  33. # IRIX apparently turns \n into \r\n.
  34. if data.endswith('\r\n'):
  35. return data.replace('\r\n', '\n')
  36. return data
  37. # Marginal testing of pty suite. Cannot do extensive 'do or fail' testing
  38. # because pty code is not too portable.
  39. # XXX(nnorwitz): these tests leak fds when there is an error.
  40. class PtyTest(unittest.TestCase):
  41. def setUp(self):
  42. # isatty() and close() can hang on some platforms. Set an alarm
  43. # before running the test to make sure we don't hang forever.
  44. self.old_alarm = signal.signal(signal.SIGALRM, self.handle_sig)
  45. signal.alarm(10)
  46. def tearDown(self):
  47. # remove alarm, restore old alarm handler
  48. signal.alarm(0)
  49. signal.signal(signal.SIGALRM, self.old_alarm)
  50. def handle_sig(self, sig, frame):
  51. self.fail("isatty hung")
  52. def test_basic(self):
  53. try:
  54. debug("Calling master_open()")
  55. master_fd, slave_name = pty.master_open()
  56. debug("Got master_fd '%d', slave_name '%s'" %
  57. (master_fd, slave_name))
  58. debug("Calling slave_open(%r)" % (slave_name,))
  59. slave_fd = pty.slave_open(slave_name)
  60. debug("Got slave_fd '%d'" % slave_fd)
  61. except OSError:
  62. # " An optional feature could not be imported " ... ?
  63. raise unittest.SkipTest, "Pseudo-terminals (seemingly) not functional."
  64. self.assertTrue(os.isatty(slave_fd), 'slave_fd is not a tty')
  65. # Solaris requires reading the fd before anything is returned.
  66. # My guess is that since we open and close the slave fd
  67. # in master_open(), we need to read the EOF.
  68. # Ensure the fd is non-blocking in case there's nothing to read.
  69. orig_flags = fcntl.fcntl(master_fd, fcntl.F_GETFL)
  70. fcntl.fcntl(master_fd, fcntl.F_SETFL, orig_flags | os.O_NONBLOCK)
  71. try:
  72. s1 = os.read(master_fd, 1024)
  73. self.assertEqual('', s1)
  74. except OSError, e:
  75. if e.errno != errno.EAGAIN:
  76. raise
  77. # Restore the original flags.
  78. fcntl.fcntl(master_fd, fcntl.F_SETFL, orig_flags)
  79. debug("Writing to slave_fd")
  80. os.write(slave_fd, TEST_STRING_1)
  81. s1 = os.read(master_fd, 1024)
  82. self.assertEqual('I wish to buy a fish license.\n',
  83. normalize_output(s1))
  84. debug("Writing chunked output")
  85. os.write(slave_fd, TEST_STRING_2[:5])
  86. os.write(slave_fd, TEST_STRING_2[5:])
  87. s2 = os.read(master_fd, 1024)
  88. self.assertEqual('For my pet fish, Eric.\n', normalize_output(s2))
  89. os.close(slave_fd)
  90. os.close(master_fd)
  91. def test_fork(self):
  92. debug("calling pty.fork()")
  93. pid, master_fd = pty.fork()
  94. if pid == pty.CHILD:
  95. # stdout should be connected to a tty.
  96. if not os.isatty(1):
  97. debug("Child's fd 1 is not a tty?!")
  98. os._exit(3)
  99. # After pty.fork(), the child should already be a session leader.
  100. # (on those systems that have that concept.)
  101. debug("In child, calling os.setsid()")
  102. try:
  103. os.setsid()
  104. except OSError:
  105. # Good, we already were session leader
  106. debug("Good: OSError was raised.")
  107. pass
  108. except AttributeError:
  109. # Have pty, but not setsid()?
  110. debug("No setsid() available?")
  111. pass
  112. except:
  113. # We don't want this error to propagate, escaping the call to
  114. # os._exit() and causing very peculiar behavior in the calling
  115. # regrtest.py !
  116. # Note: could add traceback printing here.
  117. debug("An unexpected error was raised.")
  118. os._exit(1)
  119. else:
  120. debug("os.setsid() succeeded! (bad!)")
  121. os._exit(2)
  122. os._exit(4)
  123. else:
  124. debug("Waiting for child (%d) to finish." % pid)
  125. # In verbose mode, we have to consume the debug output from the
  126. # child or the child will block, causing this test to hang in the
  127. # parent's waitpid() call. The child blocks after a
  128. # platform-dependent amount of data is written to its fd. On
  129. # Linux 2.6, it's 4000 bytes and the child won't block, but on OS
  130. # X even the small writes in the child above will block it. Also
  131. # on Linux, the read() will raise an OSError (input/output error)
  132. # when it tries to read past the end of the buffer but the child's
  133. # already exited, so catch and discard those exceptions. It's not
  134. # worth checking for EIO.
  135. while True:
  136. try:
  137. data = os.read(master_fd, 80)
  138. except OSError:
  139. break
  140. if not data:
  141. break
  142. sys.stdout.write(data.replace('\r\n', '\n'))
  143. ##line = os.read(master_fd, 80)
  144. ##lines = line.replace('\r\n', '\n').split('\n')
  145. ##if False and lines != ['In child, calling os.setsid()',
  146. ## 'Good: OSError was raised.', '']:
  147. ## raise TestFailed("Unexpected output from child: %r" % line)
  148. (pid, status) = os.waitpid(pid, 0)
  149. res = status >> 8
  150. debug("Child (%d) exited with status %d (%d)." % (pid, res, status))
  151. if res == 1:
  152. self.fail("Child raised an unexpected exception in os.setsid()")
  153. elif res == 2:
  154. self.fail("pty.fork() failed to make child a session leader.")
  155. elif res == 3:
  156. self.fail("Child spawned by pty.fork() did not have a tty as stdout")
  157. elif res != 4:
  158. self.fail("pty.fork() failed for unknown reasons.")
  159. ##debug("Reading from master_fd now that the child has exited")
  160. ##try:
  161. ## s1 = os.read(master_fd, 1024)
  162. ##except os.error:
  163. ## pass
  164. ##else:
  165. ## raise TestFailed("Read from master_fd did not raise exception")
  166. os.close(master_fd)
  167. # pty.fork() passed.
  168. class SmallPtyTests(unittest.TestCase):
  169. """These tests don't spawn children or hang."""
  170. def setUp(self):
  171. self.orig_stdin_fileno = pty.STDIN_FILENO
  172. self.orig_stdout_fileno = pty.STDOUT_FILENO
  173. self.orig_pty_select = pty.select
  174. self.fds = [] # A list of file descriptors to close.
  175. self.select_rfds_lengths = []
  176. self.select_rfds_results = []
  177. def tearDown(self):
  178. pty.STDIN_FILENO = self.orig_stdin_fileno
  179. pty.STDOUT_FILENO = self.orig_stdout_fileno
  180. pty.select = self.orig_pty_select
  181. for fd in self.fds:
  182. try:
  183. os.close(fd)
  184. except:
  185. pass
  186. def _pipe(self):
  187. pipe_fds = os.pipe()
  188. self.fds.extend(pipe_fds)
  189. return pipe_fds
  190. def _mock_select(self, rfds, wfds, xfds):
  191. # This will raise IndexError when no more expected calls exist.
  192. self.assertEqual(self.select_rfds_lengths.pop(0), len(rfds))
  193. return self.select_rfds_results.pop(0), [], []
  194. def test__copy_to_each(self):
  195. """Test the normal data case on both master_fd and stdin."""
  196. read_from_stdout_fd, mock_stdout_fd = self._pipe()
  197. pty.STDOUT_FILENO = mock_stdout_fd
  198. mock_stdin_fd, write_to_stdin_fd = self._pipe()
  199. pty.STDIN_FILENO = mock_stdin_fd
  200. socketpair = socket.socketpair()
  201. masters = [s.fileno() for s in socketpair]
  202. self.fds.extend(masters)
  203. # Feed data. Smaller than PIPEBUF. These writes will not block.
  204. os.write(masters[1], b'from master')
  205. os.write(write_to_stdin_fd, b'from stdin')
  206. # Expect two select calls, the last one will cause IndexError
  207. pty.select = self._mock_select
  208. self.select_rfds_lengths.append(2)
  209. self.select_rfds_results.append([mock_stdin_fd, masters[0]])
  210. self.select_rfds_lengths.append(2)
  211. with self.assertRaises(IndexError):
  212. pty._copy(masters[0])
  213. # Test that the right data went to the right places.
  214. rfds = select.select([read_from_stdout_fd, masters[1]], [], [], 0)[0]
  215. self.assertEqual([read_from_stdout_fd, masters[1]], rfds)
  216. self.assertEqual(os.read(read_from_stdout_fd, 20), b'from master')
  217. self.assertEqual(os.read(masters[1], 20), b'from stdin')
  218. def test__copy_eof_on_all(self):
  219. """Test the empty read EOF case on both master_fd and stdin."""
  220. read_from_stdout_fd, mock_stdout_fd = self._pipe()
  221. pty.STDOUT_FILENO = mock_stdout_fd
  222. mock_stdin_fd, write_to_stdin_fd = self._pipe()
  223. pty.STDIN_FILENO = mock_stdin_fd
  224. socketpair = socket.socketpair()
  225. masters = [s.fileno() for s in socketpair]
  226. self.fds.extend(masters)
  227. os.close(masters[1])
  228. socketpair[1].close()
  229. os.close(write_to_stdin_fd)
  230. # Expect two select calls, the last one will cause IndexError
  231. pty.select = self._mock_select
  232. self.select_rfds_lengths.append(2)
  233. self.select_rfds_results.append([mock_stdin_fd, masters[0]])
  234. # We expect that both fds were removed from the fds list as they
  235. # both encountered an EOF before the second select call.
  236. self.select_rfds_lengths.append(0)
  237. with self.assertRaises(IndexError):
  238. pty._copy(masters[0])
  239. def test_main(verbose=None):
  240. run_unittest(SmallPtyTests, PtyTest)
  241. if __name__ == "__main__":
  242. test_main()