blob: 7585c42bf0133880e8757a08db116d14d5dbf140 [file] [log] [blame]
Hai Shia089d212020-07-06 17:15:08 +08001from test.support import verbose, reap_children
2from test.support.import_helper import import_module
R. David Murrayeb3615d2009-04-22 02:24:39 +00003
Victor Stinner1db9e7b2014-07-29 22:32:47 +02004# Skip these tests if termios is not available
R. David Murrayeb3615d2009-04-22 02:24:39 +00005import_module('termios')
6
Guido van Rossum360e4b82007-05-14 22:51:27 +00007import errno
R. David Murrayeb3615d2009-04-22 02:24:39 +00008import pty
Guido van Rossumd8faa362007-04-27 19:54:29 +00009import os
10import sys
Gregory P. Smith05f59532012-02-16 00:29:12 -080011import select
Guido van Rossumd8faa362007-04-27 19:54:29 +000012import signal
Gregory P. Smith05f59532012-02-16 00:29:12 -080013import socket
Cornelius Diekmanne6f62f62017-10-02 11:39:55 +020014import io # readline
Guido van Rossumd8faa362007-04-27 19:54:29 +000015import unittest
Fred Drake4c136ee2000-06-30 23:22:35 +000016
Soumendra Gangulyc13d8992020-11-25 07:41:25 -060017import struct
18import tty
19import fcntl
Soumendra Gangulyc13d8992020-11-25 07:41:25 -060020import warnings
21
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000022TEST_STRING_1 = b"I wish to buy a fish license.\n"
23TEST_STRING_2 = b"For my pet fish, Eric.\n"
Fred Drake4c136ee2000-06-30 23:22:35 +000024
Soumendra Gangulyc13d8992020-11-25 07:41:25 -060025try:
26 _TIOCGWINSZ = tty.TIOCGWINSZ
27 _TIOCSWINSZ = tty.TIOCSWINSZ
28 _HAVE_WINSZ = True
29except AttributeError:
30 _HAVE_WINSZ = False
31
Fred Drake4c136ee2000-06-30 23:22:35 +000032if verbose:
33 def debug(msg):
Guido van Rossumbe19ed72007-02-09 05:37:30 +000034 print(msg)
Fred Drake4c136ee2000-06-30 23:22:35 +000035else:
36 def debug(msg):
37 pass
38
Guido van Rossumd8faa362007-04-27 19:54:29 +000039
Cornelius Diekmanne6f62f62017-10-02 11:39:55 +020040# Note that os.read() is nondeterministic so we need to be very careful
41# to make the test suite deterministic. A normal call to os.read() may
42# give us less than expected.
43#
44# Beware, on my Linux system, if I put 'foo\n' into a terminal fd, I get
45# back 'foo\r\n' at the other end. The behavior depends on the termios
46# setting. The newline translation may be OS-specific. To make the
47# test suite deterministic and OS-independent, the functions _readline
48# and normalize_output can be used.
49
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000050def normalize_output(data):
Benjamin Peterson06930632017-09-04 16:36:05 -070051 # Some operating systems do conversions on newline. We could possibly fix
52 # that by doing the appropriate termios.tcsetattr()s. I couldn't figure out
53 # the right combo on Tru64. So, just normalize the output and doc the
54 # problem O/Ses by allowing certain combinations for some platforms, but
55 # avoid allowing other differences (like extra whitespace, trailing garbage,
56 # etc.)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000057
58 # This is about the best we can do without getting some feedback
59 # from someone more knowledgable.
60
61 # OSF/1 (Tru64) apparently turns \n into \r\r\n.
Walter Dörwald812d8342007-05-29 18:57:42 +000062 if data.endswith(b'\r\r\n'):
63 return data.replace(b'\r\r\n', b'\n')
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000064
Walter Dörwald812d8342007-05-29 18:57:42 +000065 if data.endswith(b'\r\n'):
66 return data.replace(b'\r\n', b'\n')
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000067
68 return data
69
Cornelius Diekmanne6f62f62017-10-02 11:39:55 +020070def _readline(fd):
71 """Read one line. May block forever if no newline is read."""
72 reader = io.FileIO(fd, mode='rb', closefd=False)
73 return reader.readline()
74
Soumendra Gangulyc13d8992020-11-25 07:41:25 -060075def expectedFailureIfStdinIsTTY(fun):
Soumendra Gangulyf5a19ea2020-11-27 04:16:41 -060076 # avoid isatty()
Soumendra Gangulyc13d8992020-11-25 07:41:25 -060077 try:
78 tty.tcgetattr(pty.STDIN_FILENO)
79 return unittest.expectedFailure(fun)
80 except tty.error:
81 pass
82 return fun
83
Soumendra Gangulyc13d8992020-11-25 07:41:25 -060084def _get_term_winsz(fd):
85 s = struct.pack("HHHH", 0, 0, 0, 0)
86 return fcntl.ioctl(fd, _TIOCGWINSZ, s)
87
88def _set_term_winsz(fd, winsz):
89 fcntl.ioctl(fd, _TIOCSWINSZ, winsz)
Cornelius Diekmanne6f62f62017-10-02 11:39:55 +020090
Guido van Rossumd8faa362007-04-27 19:54:29 +000091
Fred Drake4c136ee2000-06-30 23:22:35 +000092# Marginal testing of pty suite. Cannot do extensive 'do or fail' testing
93# because pty code is not too portable.
Guido van Rossumd8faa362007-04-27 19:54:29 +000094class PtyTest(unittest.TestCase):
95 def setUp(self):
Victor Stinner9abee722017-09-19 09:36:54 -070096 old_alarm = signal.signal(signal.SIGALRM, self.handle_sig)
97 self.addCleanup(signal.signal, signal.SIGALRM, old_alarm)
Victor Stinnera1838ec2019-12-09 11:57:05 +010098
99 old_sighup = signal.signal(signal.SIGHUP, self.handle_sighup)
Victor Stinner7a51a7e2020-04-03 00:40:25 +0200100 self.addCleanup(signal.signal, signal.SIGHUP, old_sighup)
Victor Stinnera1838ec2019-12-09 11:57:05 +0100101
102 # isatty() and close() can hang on some platforms. Set an alarm
103 # before running the test to make sure we don't hang forever.
Victor Stinner9abee722017-09-19 09:36:54 -0700104 self.addCleanup(signal.alarm, 0)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000105 signal.alarm(10)
Fred Drake4c136ee2000-06-30 23:22:35 +0000106
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600107 # Save original stdin window size
108 self.stdin_rows = None
109 self.stdin_cols = None
110 if _HAVE_WINSZ:
111 try:
112 stdin_dim = os.get_terminal_size(pty.STDIN_FILENO)
113 self.stdin_rows = stdin_dim.lines
114 self.stdin_cols = stdin_dim.columns
115 old_stdin_winsz = struct.pack("HHHH", self.stdin_rows,
116 self.stdin_cols, 0, 0)
117 self.addCleanup(_set_term_winsz, pty.STDIN_FILENO, old_stdin_winsz)
118 except OSError:
119 pass
120
Guido van Rossumd8faa362007-04-27 19:54:29 +0000121 def handle_sig(self, sig, frame):
122 self.fail("isatty hung")
Neal Norwitz7d814522003-03-21 01:39:14 +0000123
Victor Stinnera1838ec2019-12-09 11:57:05 +0100124 @staticmethod
Victor Stinner7a51a7e2020-04-03 00:40:25 +0200125 def handle_sighup(signum, frame):
126 # bpo-38547: if the process is the session leader, os.close(master_fd)
Victor Stinnera1838ec2019-12-09 11:57:05 +0100127 # of "master_fd, slave_name = pty.master_open()" raises SIGHUP
128 # signal: just ignore the signal.
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600129 #
130 # NOTE: the above comment is from an older version of the test;
131 # master_open() is not being used anymore.
Victor Stinnera1838ec2019-12-09 11:57:05 +0100132 pass
133
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600134 @expectedFailureIfStdinIsTTY
135 def test_openpty(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000136 try:
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600137 mode = tty.tcgetattr(pty.STDIN_FILENO)
138 except tty.error:
139 # not a tty or bad/closed fd
140 debug("tty.tcgetattr(pty.STDIN_FILENO) failed")
141 mode = None
142
143 new_stdin_winsz = None
144 if self.stdin_rows != None and self.stdin_cols != None:
145 try:
Soumendra Gangulyf5a19ea2020-11-27 04:16:41 -0600146 # Modify pty.STDIN_FILENO window size; we need to
147 # check if pty.openpty() is able to set pty slave
148 # window size accordingly.
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600149 debug("Setting pty.STDIN_FILENO window size")
Soumendra Gangulyf5a19ea2020-11-27 04:16:41 -0600150 debug(f"original size: (rows={self.stdin_rows}, cols={self.stdin_cols})")
151 target_stdin_rows = self.stdin_rows + 1
152 target_stdin_cols = self.stdin_cols + 1
153 debug(f"target size: (rows={target_stdin_rows}, cols={target_stdin_cols})")
154 target_stdin_winsz = struct.pack("HHHH", target_stdin_rows,
155 target_stdin_cols, 0, 0)
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600156 _set_term_winsz(pty.STDIN_FILENO, target_stdin_winsz)
157
158 # Were we able to set the window size
159 # of pty.STDIN_FILENO successfully?
160 new_stdin_winsz = _get_term_winsz(pty.STDIN_FILENO)
161 self.assertEqual(new_stdin_winsz, target_stdin_winsz,
162 "pty.STDIN_FILENO window size unchanged")
163 except OSError:
164 warnings.warn("Failed to set pty.STDIN_FILENO window size")
165 pass
166
167 try:
168 debug("Calling pty.openpty()")
169 try:
170 master_fd, slave_fd = pty.openpty(mode, new_stdin_winsz)
171 except TypeError:
172 master_fd, slave_fd = pty.openpty()
173 debug(f"Got master_fd '{master_fd}', slave_fd '{slave_fd}'")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000174 except OSError:
175 # " An optional feature could not be imported " ... ?
Benjamin Petersone549ead2009-03-28 21:42:05 +0000176 raise unittest.SkipTest("Pseudo-terminals (seemingly) not functional.")
Neal Norwitz7d814522003-03-21 01:39:14 +0000177
Petr Viktorin65cf1ad2021-01-19 14:03:12 +0100178 # closing master_fd can raise a SIGHUP if the process is
179 # the session leader: we installed a SIGHUP signal handler
180 # to ignore this signal.
181 self.addCleanup(os.close, master_fd)
182 self.addCleanup(os.close, slave_fd)
183
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600184 self.assertTrue(os.isatty(slave_fd), "slave_fd is not a tty")
185
186 if mode:
187 self.assertEqual(tty.tcgetattr(slave_fd), mode,
188 "openpty() failed to set slave termios")
189 if new_stdin_winsz:
190 self.assertEqual(_get_term_winsz(slave_fd), new_stdin_winsz,
191 "openpty() failed to set slave window size")
Neal Norwitz7d814522003-03-21 01:39:14 +0000192
Guido van Rossum360e4b82007-05-14 22:51:27 +0000193 # Solaris requires reading the fd before anything is returned.
194 # My guess is that since we open and close the slave fd
195 # in master_open(), we need to read the EOF.
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600196 #
197 # NOTE: the above comment is from an older version of the test;
198 # master_open() is not being used anymore.
Guido van Rossum360e4b82007-05-14 22:51:27 +0000199
200 # Ensure the fd is non-blocking in case there's nothing to read.
Victor Stinner1db9e7b2014-07-29 22:32:47 +0200201 blocking = os.get_blocking(master_fd)
Guido van Rossum360e4b82007-05-14 22:51:27 +0000202 try:
Victor Stinner1db9e7b2014-07-29 22:32:47 +0200203 os.set_blocking(master_fd, False)
204 try:
205 s1 = os.read(master_fd, 1024)
206 self.assertEqual(b'', s1)
207 except OSError as e:
208 if e.errno != errno.EAGAIN:
209 raise
210 finally:
211 # Restore the original flags.
212 os.set_blocking(master_fd, blocking)
Guido van Rossum360e4b82007-05-14 22:51:27 +0000213
Guido van Rossumd8faa362007-04-27 19:54:29 +0000214 debug("Writing to slave_fd")
215 os.write(slave_fd, TEST_STRING_1)
Cornelius Diekmanne6f62f62017-10-02 11:39:55 +0200216 s1 = _readline(master_fd)
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000217 self.assertEqual(b'I wish to buy a fish license.\n',
218 normalize_output(s1))
Neal Norwitz7d814522003-03-21 01:39:14 +0000219
Guido van Rossumd8faa362007-04-27 19:54:29 +0000220 debug("Writing chunked output")
221 os.write(slave_fd, TEST_STRING_2[:5])
222 os.write(slave_fd, TEST_STRING_2[5:])
Cornelius Diekmanne6f62f62017-10-02 11:39:55 +0200223 s2 = _readline(master_fd)
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000224 self.assertEqual(b'For my pet fish, Eric.\n', normalize_output(s2))
Neal Norwitz7d814522003-03-21 01:39:14 +0000225
Guido van Rossumd8faa362007-04-27 19:54:29 +0000226 def test_fork(self):
227 debug("calling pty.fork()")
228 pid, master_fd = pty.fork()
Petr Viktorin65cf1ad2021-01-19 14:03:12 +0100229 self.addCleanup(os.close, master_fd)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000230 if pid == pty.CHILD:
231 # stdout should be connected to a tty.
232 if not os.isatty(1):
233 debug("Child's fd 1 is not a tty?!")
234 os._exit(3)
Fred Drake4c136ee2000-06-30 23:22:35 +0000235
Guido van Rossumd8faa362007-04-27 19:54:29 +0000236 # After pty.fork(), the child should already be a session leader.
237 # (on those systems that have that concept.)
238 debug("In child, calling os.setsid()")
239 try:
240 os.setsid()
241 except OSError:
242 # Good, we already were session leader
243 debug("Good: OSError was raised.")
244 pass
245 except AttributeError:
246 # Have pty, but not setsid()?
247 debug("No setsid() available?")
248 pass
249 except:
250 # We don't want this error to propagate, escaping the call to
251 # os._exit() and causing very peculiar behavior in the calling
252 # regrtest.py !
253 # Note: could add traceback printing here.
254 debug("An unexpected error was raised.")
255 os._exit(1)
256 else:
257 debug("os.setsid() succeeded! (bad!)")
258 os._exit(2)
259 os._exit(4)
260 else:
261 debug("Waiting for child (%d) to finish." % pid)
262 # In verbose mode, we have to consume the debug output from the
263 # child or the child will block, causing this test to hang in the
264 # parent's waitpid() call. The child blocks after a
265 # platform-dependent amount of data is written to its fd. On
266 # Linux 2.6, it's 4000 bytes and the child won't block, but on OS
267 # X even the small writes in the child above will block it. Also
Andrew Svetlov737fb892012-12-18 21:14:22 +0200268 # on Linux, the read() will raise an OSError (input/output error)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000269 # when it tries to read past the end of the buffer but the child's
270 # already exited, so catch and discard those exceptions. It's not
271 # worth checking for EIO.
272 while True:
273 try:
274 data = os.read(master_fd, 80)
275 except OSError:
276 break
277 if not data:
278 break
Alexandre Vassalottia351f772008-03-03 02:59:49 +0000279 sys.stdout.write(str(data.replace(b'\r\n', b'\n'),
280 encoding='ascii'))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000281
282 ##line = os.read(master_fd, 80)
283 ##lines = line.replace('\r\n', '\n').split('\n')
284 ##if False and lines != ['In child, calling os.setsid()',
285 ## 'Good: OSError was raised.', '']:
286 ## raise TestFailed("Unexpected output from child: %r" % line)
287
288 (pid, status) = os.waitpid(pid, 0)
Victor Stinner65a796e2020-04-01 18:49:29 +0200289 res = os.waitstatus_to_exitcode(status)
290 debug("Child (%d) exited with code %d (status %d)." % (pid, res, status))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000291 if res == 1:
292 self.fail("Child raised an unexpected exception in os.setsid()")
293 elif res == 2:
294 self.fail("pty.fork() failed to make child a session leader.")
295 elif res == 3:
296 self.fail("Child spawned by pty.fork() did not have a tty as stdout")
297 elif res != 4:
298 self.fail("pty.fork() failed for unknown reasons.")
299
300 ##debug("Reading from master_fd now that the child has exited")
301 ##try:
302 ## s1 = os.read(master_fd, 1024)
Andrew Svetlov8b33dd82012-12-24 19:58:48 +0200303 ##except OSError:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000304 ## pass
305 ##else:
306 ## raise TestFailed("Read from master_fd did not raise exception")
307
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600308 def test_master_read(self):
Petr Viktorin65cf1ad2021-01-19 14:03:12 +0100309 # XXX(nnorwitz): this test leaks fds when there is an error.
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600310 debug("Calling pty.openpty()")
311 master_fd, slave_fd = pty.openpty()
312 debug(f"Got master_fd '{master_fd}', slave_fd '{slave_fd}'")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000313
Petr Viktorin65cf1ad2021-01-19 14:03:12 +0100314 self.addCleanup(os.close, master_fd)
315
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600316 debug("Closing slave_fd")
317 os.close(slave_fd)
318
319 debug("Reading from master_fd")
Soumendra Ganguly74311ae2020-11-28 15:04:20 -0600320 try:
321 data = os.read(master_fd, 1)
322 except OSError: # Linux
323 data = b""
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600324
Soumendra Ganguly74311ae2020-11-28 15:04:20 -0600325 self.assertEqual(data, b"")
Gregory P. Smith05f59532012-02-16 00:29:12 -0800326
327class SmallPtyTests(unittest.TestCase):
328 """These tests don't spawn children or hang."""
329
330 def setUp(self):
331 self.orig_stdin_fileno = pty.STDIN_FILENO
332 self.orig_stdout_fileno = pty.STDOUT_FILENO
333 self.orig_pty_select = pty.select
334 self.fds = [] # A list of file descriptors to close.
Victor Stinnerb1f7f632012-03-06 02:04:58 +0100335 self.files = []
Gregory P. Smith05f59532012-02-16 00:29:12 -0800336 self.select_rfds_lengths = []
337 self.select_rfds_results = []
338
339 def tearDown(self):
340 pty.STDIN_FILENO = self.orig_stdin_fileno
341 pty.STDOUT_FILENO = self.orig_stdout_fileno
342 pty.select = self.orig_pty_select
Victor Stinnerb1f7f632012-03-06 02:04:58 +0100343 for file in self.files:
344 try:
345 file.close()
346 except OSError:
347 pass
Gregory P. Smith05f59532012-02-16 00:29:12 -0800348 for fd in self.fds:
349 try:
350 os.close(fd)
Victor Stinnerb1f7f632012-03-06 02:04:58 +0100351 except OSError:
Gregory P. Smith05f59532012-02-16 00:29:12 -0800352 pass
353
354 def _pipe(self):
355 pipe_fds = os.pipe()
356 self.fds.extend(pipe_fds)
357 return pipe_fds
358
Victor Stinnerb1f7f632012-03-06 02:04:58 +0100359 def _socketpair(self):
360 socketpair = socket.socketpair()
361 self.files.extend(socketpair)
362 return socketpair
363
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600364 def _mock_select(self, rfds, wfds, xfds, timeout=0):
Gregory P. Smith05f59532012-02-16 00:29:12 -0800365 # This will raise IndexError when no more expected calls exist.
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600366 # This ignores the timeout
Gregory P. Smith05f59532012-02-16 00:29:12 -0800367 self.assertEqual(self.select_rfds_lengths.pop(0), len(rfds))
368 return self.select_rfds_results.pop(0), [], []
369
370 def test__copy_to_each(self):
371 """Test the normal data case on both master_fd and stdin."""
372 read_from_stdout_fd, mock_stdout_fd = self._pipe()
373 pty.STDOUT_FILENO = mock_stdout_fd
374 mock_stdin_fd, write_to_stdin_fd = self._pipe()
375 pty.STDIN_FILENO = mock_stdin_fd
Victor Stinnerb1f7f632012-03-06 02:04:58 +0100376 socketpair = self._socketpair()
Gregory P. Smith05f59532012-02-16 00:29:12 -0800377 masters = [s.fileno() for s in socketpair]
Gregory P. Smith05f59532012-02-16 00:29:12 -0800378
379 # Feed data. Smaller than PIPEBUF. These writes will not block.
380 os.write(masters[1], b'from master')
381 os.write(write_to_stdin_fd, b'from stdin')
382
383 # Expect two select calls, the last one will cause IndexError
384 pty.select = self._mock_select
385 self.select_rfds_lengths.append(2)
386 self.select_rfds_results.append([mock_stdin_fd, masters[0]])
387 self.select_rfds_lengths.append(2)
388
389 with self.assertRaises(IndexError):
390 pty._copy(masters[0])
391
392 # Test that the right data went to the right places.
393 rfds = select.select([read_from_stdout_fd, masters[1]], [], [], 0)[0]
Gregory P. Smith5b791fb2012-02-16 00:35:43 -0800394 self.assertEqual([read_from_stdout_fd, masters[1]], rfds)
Gregory P. Smith05f59532012-02-16 00:29:12 -0800395 self.assertEqual(os.read(read_from_stdout_fd, 20), b'from master')
396 self.assertEqual(os.read(masters[1], 20), b'from stdin')
397
398 def test__copy_eof_on_all(self):
399 """Test the empty read EOF case on both master_fd and stdin."""
400 read_from_stdout_fd, mock_stdout_fd = self._pipe()
401 pty.STDOUT_FILENO = mock_stdout_fd
402 mock_stdin_fd, write_to_stdin_fd = self._pipe()
403 pty.STDIN_FILENO = mock_stdin_fd
Victor Stinnerb1f7f632012-03-06 02:04:58 +0100404 socketpair = self._socketpair()
Gregory P. Smith05f59532012-02-16 00:29:12 -0800405 masters = [s.fileno() for s in socketpair]
Gregory P. Smith05f59532012-02-16 00:29:12 -0800406
Gregory P. Smith05f59532012-02-16 00:29:12 -0800407 socketpair[1].close()
408 os.close(write_to_stdin_fd)
409
410 # Expect two select calls, the last one will cause IndexError
411 pty.select = self._mock_select
412 self.select_rfds_lengths.append(2)
413 self.select_rfds_results.append([mock_stdin_fd, masters[0]])
414 # We expect that both fds were removed from the fds list as they
415 # both encountered an EOF before the second select call.
416 self.select_rfds_lengths.append(0)
417
418 with self.assertRaises(IndexError):
419 pty._copy(masters[0])
420
421
Zachary Ware38c707e2015-04-13 15:00:43 -0500422def tearDownModule():
423 reap_children()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000424
425if __name__ == "__main__":
Zachary Ware38c707e2015-04-13 15:00:43 -0500426 unittest.main()