(root)/
Python-3.11.7/
Lib/
test/
test_pty.py
       1  from test.support import verbose, reap_children
       2  from test.support.import_helper import import_module
       3  
       4  # Skip these tests if termios or fcntl are not available
       5  import_module('termios')
       6  # fcntl is a proxy for not being one of the wasm32 platforms even though we
       7  # don't use this module... a proper check for what crashes those is needed.
       8  import_module("fcntl")
       9  
      10  import errno
      11  import os
      12  import pty
      13  import tty
      14  import sys
      15  import select
      16  import signal
      17  import socket
      18  import io # readline
      19  import unittest
      20  import warnings
      21  
      22  TEST_STRING_1 = b"I wish to buy a fish license.\n"
      23  TEST_STRING_2 = b"For my pet fish, Eric.\n"
      24  
      25  _HAVE_WINSZ = hasattr(tty, "TIOCGWINSZ") and hasattr(tty, "TIOCSWINSZ")
      26  
      27  if verbose:
      28      def debug(msg):
      29          print(msg)
      30  else:
      31      def debug(msg):
      32          pass
      33  
      34  
      35  # Note that os.read() is nondeterministic so we need to be very careful
      36  # to make the test suite deterministic.  A normal call to os.read() may
      37  # give us less than expected.
      38  #
      39  # Beware, on my Linux system, if I put 'foo\n' into a terminal fd, I get
      40  # back 'foo\r\n' at the other end.  The behavior depends on the termios
      41  # setting.  The newline translation may be OS-specific.  To make the
      42  # test suite deterministic and OS-independent, the functions _readline
      43  # and normalize_output can be used.
      44  
      45  def normalize_output(data):
      46      # Some operating systems do conversions on newline.  We could possibly fix
      47      # that by doing the appropriate termios.tcsetattr()s.  I couldn't figure out
      48      # the right combo on Tru64.  So, just normalize the output and doc the
      49      # problem O/Ses by allowing certain combinations for some platforms, but
      50      # avoid allowing other differences (like extra whitespace, trailing garbage,
      51      # etc.)
      52  
      53      # This is about the best we can do without getting some feedback
      54      # from someone more knowledgable.
      55  
      56      # OSF/1 (Tru64) apparently turns \n into \r\r\n.
      57      if data.endswith(b'\r\r\n'):
      58          return data.replace(b'\r\r\n', b'\n')
      59  
      60      if data.endswith(b'\r\n'):
      61          return data.replace(b'\r\n', b'\n')
      62  
      63      return data
      64  
      65  def _readline(fd):
      66      """Read one line.  May block forever if no newline is read."""
      67      reader = io.FileIO(fd, mode='rb', closefd=False)
      68      return reader.readline()
      69  
      70  def expectedFailureIfStdinIsTTY(fun):
      71      # avoid isatty()
      72      try:
      73          tty.tcgetattr(pty.STDIN_FILENO)
      74          return unittest.expectedFailure(fun)
      75      except tty.error:
      76          pass
      77      return fun
      78  
      79  
      80  def write_all(fd, data):
      81      written = os.write(fd, data)
      82      if written != len(data):
      83          # gh-73256, gh-110673: It should never happen, but check just in case
      84          raise Exception(f"short write: os.write({fd}, {len(data)} bytes) "
      85                          f"wrote {written} bytes")
      86  
      87  
      88  # Marginal testing of pty suite. Cannot do extensive 'do or fail' testing
      89  # because pty code is not too portable.
      90  class ESC[4;38;5;81mPtyTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
      91      def setUp(self):
      92          old_sighup = signal.signal(signal.SIGHUP, self.handle_sighup)
      93          self.addCleanup(signal.signal, signal.SIGHUP, old_sighup)
      94  
      95          # Save original stdin window size.
      96          self.stdin_dim = None
      97          if _HAVE_WINSZ:
      98              try:
      99                  self.stdin_dim = tty.tcgetwinsize(pty.STDIN_FILENO)
     100                  self.addCleanup(tty.tcsetwinsize, pty.STDIN_FILENO,
     101                                  self.stdin_dim)
     102              except tty.error:
     103                  pass
     104  
     105      @staticmethod
     106      def handle_sighup(signum, frame):
     107          pass
     108  
     109      @expectedFailureIfStdinIsTTY
     110      def test_openpty(self):
     111          try:
     112              mode = tty.tcgetattr(pty.STDIN_FILENO)
     113          except tty.error:
     114              # Not a tty or bad/closed fd.
     115              debug("tty.tcgetattr(pty.STDIN_FILENO) failed")
     116              mode = None
     117  
     118          new_dim = None
     119          if self.stdin_dim:
     120              try:
     121                  # Modify pty.STDIN_FILENO window size; we need to
     122                  # check if pty.openpty() is able to set pty slave
     123                  # window size accordingly.
     124                  debug("Setting pty.STDIN_FILENO window size.")
     125                  debug(f"original size: (row, col) = {self.stdin_dim}")
     126                  target_dim = (self.stdin_dim[0] + 1, self.stdin_dim[1] + 1)
     127                  debug(f"target size: (row, col) = {target_dim}")
     128                  tty.tcsetwinsize(pty.STDIN_FILENO, target_dim)
     129  
     130                  # Were we able to set the window size
     131                  # of pty.STDIN_FILENO successfully?
     132                  new_dim = tty.tcgetwinsize(pty.STDIN_FILENO)
     133                  self.assertEqual(new_dim, target_dim,
     134                                   "pty.STDIN_FILENO window size unchanged")
     135              except OSError:
     136                  warnings.warn("Failed to set pty.STDIN_FILENO window size.")
     137                  pass
     138  
     139          try:
     140              debug("Calling pty.openpty()")
     141              try:
     142                  master_fd, slave_fd, slave_name = pty.openpty(mode, new_dim,
     143                                                                True)
     144              except TypeError:
     145                  master_fd, slave_fd = pty.openpty()
     146                  slave_name = None
     147              debug(f"Got {master_fd=}, {slave_fd=}, {slave_name=}")
     148          except OSError:
     149              # " An optional feature could not be imported " ... ?
     150              raise unittest.SkipTest("Pseudo-terminals (seemingly) not functional.")
     151  
     152          # closing master_fd can raise a SIGHUP if the process is
     153          # the session leader: we installed a SIGHUP signal handler
     154          # to ignore this signal.
     155          self.addCleanup(os.close, master_fd)
     156          self.addCleanup(os.close, slave_fd)
     157  
     158          self.assertTrue(os.isatty(slave_fd), "slave_fd is not a tty")
     159  
     160          if mode:
     161              self.assertEqual(tty.tcgetattr(slave_fd), mode,
     162                               "openpty() failed to set slave termios")
     163          if new_dim:
     164              self.assertEqual(tty.tcgetwinsize(slave_fd), new_dim,
     165                               "openpty() failed to set slave window size")
     166  
     167          # Ensure the fd is non-blocking in case there's nothing to read.
     168          blocking = os.get_blocking(master_fd)
     169          try:
     170              os.set_blocking(master_fd, False)
     171              try:
     172                  s1 = os.read(master_fd, 1024)
     173                  self.assertEqual(b'', s1)
     174              except OSError as e:
     175                  if e.errno != errno.EAGAIN:
     176                      raise
     177          finally:
     178              # Restore the original flags.
     179              os.set_blocking(master_fd, blocking)
     180  
     181          debug("Writing to slave_fd")
     182          write_all(slave_fd, TEST_STRING_1)
     183          s1 = _readline(master_fd)
     184          self.assertEqual(b'I wish to buy a fish license.\n',
     185                           normalize_output(s1))
     186  
     187          debug("Writing chunked output")
     188          write_all(slave_fd, TEST_STRING_2[:5])
     189          write_all(slave_fd, TEST_STRING_2[5:])
     190          s2 = _readline(master_fd)
     191          self.assertEqual(b'For my pet fish, Eric.\n', normalize_output(s2))
     192  
     193      def test_fork(self):
     194          debug("calling pty.fork()")
     195          pid, master_fd = pty.fork()
     196          self.addCleanup(os.close, master_fd)
     197          if pid == pty.CHILD:
     198              # stdout should be connected to a tty.
     199              if not os.isatty(1):
     200                  debug("Child's fd 1 is not a tty?!")
     201                  os._exit(3)
     202  
     203              # After pty.fork(), the child should already be a session leader.
     204              # (on those systems that have that concept.)
     205              debug("In child, calling os.setsid()")
     206              try:
     207                  os.setsid()
     208              except OSError:
     209                  # Good, we already were session leader
     210                  debug("Good: OSError was raised.")
     211                  pass
     212              except AttributeError:
     213                  # Have pty, but not setsid()?
     214                  debug("No setsid() available?")
     215                  pass
     216              except:
     217                  # We don't want this error to propagate, escaping the call to
     218                  # os._exit() and causing very peculiar behavior in the calling
     219                  # regrtest.py !
     220                  # Note: could add traceback printing here.
     221                  debug("An unexpected error was raised.")
     222                  os._exit(1)
     223              else:
     224                  debug("os.setsid() succeeded! (bad!)")
     225                  os._exit(2)
     226              os._exit(4)
     227          else:
     228              debug("Waiting for child (%d) to finish." % pid)
     229              # In verbose mode, we have to consume the debug output from the
     230              # child or the child will block, causing this test to hang in the
     231              # parent's waitpid() call.  The child blocks after a
     232              # platform-dependent amount of data is written to its fd.  On
     233              # Linux 2.6, it's 4000 bytes and the child won't block, but on OS
     234              # X even the small writes in the child above will block it.  Also
     235              # on Linux, the read() will raise an OSError (input/output error)
     236              # when it tries to read past the end of the buffer but the child's
     237              # already exited, so catch and discard those exceptions.  It's not
     238              # worth checking for EIO.
     239              while True:
     240                  try:
     241                      data = os.read(master_fd, 80)
     242                  except OSError:
     243                      break
     244                  if not data:
     245                      break
     246                  sys.stdout.write(str(data.replace(b'\r\n', b'\n'),
     247                                       encoding='ascii'))
     248  
     249              ##line = os.read(master_fd, 80)
     250              ##lines = line.replace('\r\n', '\n').split('\n')
     251              ##if False and lines != ['In child, calling os.setsid()',
     252              ##             'Good: OSError was raised.', '']:
     253              ##    raise TestFailed("Unexpected output from child: %r" % line)
     254  
     255              (pid, status) = os.waitpid(pid, 0)
     256              res = os.waitstatus_to_exitcode(status)
     257              debug("Child (%d) exited with code %d (status %d)." % (pid, res, status))
     258              if res == 1:
     259                  self.fail("Child raised an unexpected exception in os.setsid()")
     260              elif res == 2:
     261                  self.fail("pty.fork() failed to make child a session leader.")
     262              elif res == 3:
     263                  self.fail("Child spawned by pty.fork() did not have a tty as stdout")
     264              elif res != 4:
     265                  self.fail("pty.fork() failed for unknown reasons.")
     266  
     267              ##debug("Reading from master_fd now that the child has exited")
     268              ##try:
     269              ##    s1 = os.read(master_fd, 1024)
     270              ##except OSError:
     271              ##    pass
     272              ##else:
     273              ##    raise TestFailed("Read from master_fd did not raise exception")
     274  
     275      def test_master_read(self):
     276          # XXX(nnorwitz):  this test leaks fds when there is an error.
     277          debug("Calling pty.openpty()")
     278          master_fd, slave_fd = pty.openpty()
     279          debug(f"Got master_fd '{master_fd}', slave_fd '{slave_fd}'")
     280  
     281          self.addCleanup(os.close, master_fd)
     282  
     283          debug("Closing slave_fd")
     284          os.close(slave_fd)
     285  
     286          debug("Reading from master_fd")
     287          try:
     288              data = os.read(master_fd, 1)
     289          except OSError: # Linux
     290              data = b""
     291  
     292          self.assertEqual(data, b"")
     293  
     294      def test_spawn_doesnt_hang(self):
     295          pty.spawn([sys.executable, '-c', 'print("hi there")'])
     296  
     297  class ESC[4;38;5;81mSmallPtyTests(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
     298      """These tests don't spawn children or hang."""
     299  
     300      def setUp(self):
     301          self.orig_stdin_fileno = pty.STDIN_FILENO
     302          self.orig_stdout_fileno = pty.STDOUT_FILENO
     303          self.orig_pty_close = pty.close
     304          self.orig_pty__copy = pty._copy
     305          self.orig_pty_fork = pty.fork
     306          self.orig_pty_select = pty.select
     307          self.orig_pty_setraw = pty.setraw
     308          self.orig_pty_tcgetattr = pty.tcgetattr
     309          self.orig_pty_tcsetattr = pty.tcsetattr
     310          self.orig_pty_waitpid = pty.waitpid
     311          self.fds = []  # A list of file descriptors to close.
     312          self.files = []
     313          self.select_input = []
     314          self.select_output = []
     315          self.tcsetattr_mode_setting = None
     316  
     317      def tearDown(self):
     318          pty.STDIN_FILENO = self.orig_stdin_fileno
     319          pty.STDOUT_FILENO = self.orig_stdout_fileno
     320          pty.close = self.orig_pty_close
     321          pty._copy = self.orig_pty__copy
     322          pty.fork = self.orig_pty_fork
     323          pty.select = self.orig_pty_select
     324          pty.setraw = self.orig_pty_setraw
     325          pty.tcgetattr = self.orig_pty_tcgetattr
     326          pty.tcsetattr = self.orig_pty_tcsetattr
     327          pty.waitpid = self.orig_pty_waitpid
     328          for file in self.files:
     329              try:
     330                  file.close()
     331              except OSError:
     332                  pass
     333          for fd in self.fds:
     334              try:
     335                  os.close(fd)
     336              except OSError:
     337                  pass
     338  
     339      def _pipe(self):
     340          pipe_fds = os.pipe()
     341          self.fds.extend(pipe_fds)
     342          return pipe_fds
     343  
     344      def _socketpair(self):
     345          socketpair = socket.socketpair()
     346          self.files.extend(socketpair)
     347          return socketpair
     348  
     349      def _mock_select(self, rfds, wfds, xfds):
     350          # This will raise IndexError when no more expected calls exist.
     351          self.assertEqual((rfds, wfds, xfds), self.select_input.pop(0))
     352          return self.select_output.pop(0)
     353  
     354      def _make_mock_fork(self, pid):
     355          def mock_fork():
     356              return (pid, 12)
     357          return mock_fork
     358  
     359      def _mock_tcsetattr(self, fileno, opt, mode):
     360          self.tcsetattr_mode_setting = mode
     361  
     362      def test__copy_to_each(self):
     363          """Test the normal data case on both master_fd and stdin."""
     364          read_from_stdout_fd, mock_stdout_fd = self._pipe()
     365          pty.STDOUT_FILENO = mock_stdout_fd
     366          mock_stdin_fd, write_to_stdin_fd = self._pipe()
     367          pty.STDIN_FILENO = mock_stdin_fd
     368          socketpair = self._socketpair()
     369          masters = [s.fileno() for s in socketpair]
     370  
     371          # Feed data.  Smaller than PIPEBUF.  These writes will not block.
     372          write_all(masters[1], b'from master')
     373          write_all(write_to_stdin_fd, b'from stdin')
     374  
     375          # Expect three select calls, the last one will cause IndexError
     376          pty.select = self._mock_select
     377          self.select_input.append(([mock_stdin_fd, masters[0]], [], []))
     378          self.select_output.append(([mock_stdin_fd, masters[0]], [], []))
     379          self.select_input.append(([mock_stdin_fd, masters[0]], [mock_stdout_fd, masters[0]], []))
     380          self.select_output.append(([], [mock_stdout_fd, masters[0]], []))
     381          self.select_input.append(([mock_stdin_fd, masters[0]], [], []))
     382  
     383          with self.assertRaises(IndexError):
     384              pty._copy(masters[0])
     385  
     386          # Test that the right data went to the right places.
     387          rfds = select.select([read_from_stdout_fd, masters[1]], [], [], 0)[0]
     388          self.assertEqual([read_from_stdout_fd, masters[1]], rfds)
     389          self.assertEqual(os.read(read_from_stdout_fd, 20), b'from master')
     390          self.assertEqual(os.read(masters[1], 20), b'from stdin')
     391  
     392      def test__restore_tty_mode_normal_return(self):
     393          """Test that spawn resets the tty mode no when _copy returns normally."""
     394  
     395          # PID 1 is returned from mocked fork to run the parent branch
     396          # of code
     397          pty.fork = self._make_mock_fork(1)
     398  
     399          status_sentinel = object()
     400          pty.waitpid = lambda _1, _2: [None, status_sentinel]
     401          pty.close = lambda _: None
     402  
     403          pty._copy = lambda _1, _2, _3: None
     404  
     405          mode_sentinel = object()
     406          pty.tcgetattr = lambda fd: mode_sentinel
     407          pty.tcsetattr = self._mock_tcsetattr
     408          pty.setraw = lambda _: None
     409  
     410          self.assertEqual(pty.spawn([]), status_sentinel, "pty.waitpid process status not returned by pty.spawn")
     411          self.assertEqual(self.tcsetattr_mode_setting, mode_sentinel, "pty.tcsetattr not called with original mode value")
     412  
     413  
     414  def tearDownModule():
     415      reap_children()
     416  
     417  
     418  if __name__ == "__main__":
     419      unittest.main()