blob: 190d8d787a2cc99f0912d5c06f04536eb6c395fc [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 Rossum360e4b82007-05-14 22:51:27 +000094# XXX(nnorwitz): these tests leak fds when there is an error.
Guido van Rossumd8faa362007-04-27 19:54:29 +000095class PtyTest(unittest.TestCase):
96 def setUp(self):
Victor Stinner9abee722017-09-19 09:36:54 -070097 old_alarm = signal.signal(signal.SIGALRM, self.handle_sig)
98 self.addCleanup(signal.signal, signal.SIGALRM, old_alarm)
Victor Stinnera1838ec2019-12-09 11:57:05 +010099
100 old_sighup = signal.signal(signal.SIGHUP, self.handle_sighup)
Victor Stinner7a51a7e2020-04-03 00:40:25 +0200101 self.addCleanup(signal.signal, signal.SIGHUP, old_sighup)
Victor Stinnera1838ec2019-12-09 11:57:05 +0100102
103 # isatty() and close() can hang on some platforms. Set an alarm
104 # before running the test to make sure we don't hang forever.
Victor Stinner9abee722017-09-19 09:36:54 -0700105 self.addCleanup(signal.alarm, 0)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000106 signal.alarm(10)
Fred Drake4c136ee2000-06-30 23:22:35 +0000107
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600108 # Save original stdin window size
109 self.stdin_rows = None
110 self.stdin_cols = None
111 if _HAVE_WINSZ:
112 try:
113 stdin_dim = os.get_terminal_size(pty.STDIN_FILENO)
114 self.stdin_rows = stdin_dim.lines
115 self.stdin_cols = stdin_dim.columns
116 old_stdin_winsz = struct.pack("HHHH", self.stdin_rows,
117 self.stdin_cols, 0, 0)
118 self.addCleanup(_set_term_winsz, pty.STDIN_FILENO, old_stdin_winsz)
119 except OSError:
120 pass
121
Guido van Rossumd8faa362007-04-27 19:54:29 +0000122 def handle_sig(self, sig, frame):
123 self.fail("isatty hung")
Neal Norwitz7d814522003-03-21 01:39:14 +0000124
Victor Stinnera1838ec2019-12-09 11:57:05 +0100125 @staticmethod
Victor Stinner7a51a7e2020-04-03 00:40:25 +0200126 def handle_sighup(signum, frame):
127 # bpo-38547: if the process is the session leader, os.close(master_fd)
Victor Stinnera1838ec2019-12-09 11:57:05 +0100128 # of "master_fd, slave_name = pty.master_open()" raises SIGHUP
129 # signal: just ignore the signal.
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600130 #
131 # NOTE: the above comment is from an older version of the test;
132 # master_open() is not being used anymore.
Victor Stinnera1838ec2019-12-09 11:57:05 +0100133 pass
134
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600135 @expectedFailureIfStdinIsTTY
136 def test_openpty(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000137 try:
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600138 mode = tty.tcgetattr(pty.STDIN_FILENO)
139 except tty.error:
140 # not a tty or bad/closed fd
141 debug("tty.tcgetattr(pty.STDIN_FILENO) failed")
142 mode = None
143
144 new_stdin_winsz = None
145 if self.stdin_rows != None and self.stdin_cols != None:
146 try:
Soumendra Gangulyf5a19ea2020-11-27 04:16:41 -0600147 # Modify pty.STDIN_FILENO window size; we need to
148 # check if pty.openpty() is able to set pty slave
149 # window size accordingly.
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600150 debug("Setting pty.STDIN_FILENO window size")
Soumendra Gangulyf5a19ea2020-11-27 04:16:41 -0600151 debug(f"original size: (rows={self.stdin_rows}, cols={self.stdin_cols})")
152 target_stdin_rows = self.stdin_rows + 1
153 target_stdin_cols = self.stdin_cols + 1
154 debug(f"target size: (rows={target_stdin_rows}, cols={target_stdin_cols})")
155 target_stdin_winsz = struct.pack("HHHH", target_stdin_rows,
156 target_stdin_cols, 0, 0)
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600157 _set_term_winsz(pty.STDIN_FILENO, target_stdin_winsz)
158
159 # Were we able to set the window size
160 # of pty.STDIN_FILENO successfully?
161 new_stdin_winsz = _get_term_winsz(pty.STDIN_FILENO)
162 self.assertEqual(new_stdin_winsz, target_stdin_winsz,
163 "pty.STDIN_FILENO window size unchanged")
164 except OSError:
165 warnings.warn("Failed to set pty.STDIN_FILENO window size")
166 pass
167
168 try:
169 debug("Calling pty.openpty()")
170 try:
171 master_fd, slave_fd = pty.openpty(mode, new_stdin_winsz)
172 except TypeError:
173 master_fd, slave_fd = pty.openpty()
174 debug(f"Got master_fd '{master_fd}', slave_fd '{slave_fd}'")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000175 except OSError:
176 # " An optional feature could not be imported " ... ?
Benjamin Petersone549ead2009-03-28 21:42:05 +0000177 raise unittest.SkipTest("Pseudo-terminals (seemingly) not functional.")
Neal Norwitz7d814522003-03-21 01:39:14 +0000178
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600179 self.assertTrue(os.isatty(slave_fd), "slave_fd is not a tty")
180
181 if mode:
182 self.assertEqual(tty.tcgetattr(slave_fd), mode,
183 "openpty() failed to set slave termios")
184 if new_stdin_winsz:
185 self.assertEqual(_get_term_winsz(slave_fd), new_stdin_winsz,
186 "openpty() failed to set slave window size")
Neal Norwitz7d814522003-03-21 01:39:14 +0000187
Guido van Rossum360e4b82007-05-14 22:51:27 +0000188 # Solaris requires reading the fd before anything is returned.
189 # My guess is that since we open and close the slave fd
190 # in master_open(), we need to read the EOF.
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600191 #
192 # NOTE: the above comment is from an older version of the test;
193 # master_open() is not being used anymore.
Guido van Rossum360e4b82007-05-14 22:51:27 +0000194
195 # Ensure the fd is non-blocking in case there's nothing to read.
Victor Stinner1db9e7b2014-07-29 22:32:47 +0200196 blocking = os.get_blocking(master_fd)
Guido van Rossum360e4b82007-05-14 22:51:27 +0000197 try:
Victor Stinner1db9e7b2014-07-29 22:32:47 +0200198 os.set_blocking(master_fd, False)
199 try:
200 s1 = os.read(master_fd, 1024)
201 self.assertEqual(b'', s1)
202 except OSError as e:
203 if e.errno != errno.EAGAIN:
204 raise
205 finally:
206 # Restore the original flags.
207 os.set_blocking(master_fd, blocking)
Guido van Rossum360e4b82007-05-14 22:51:27 +0000208
Guido van Rossumd8faa362007-04-27 19:54:29 +0000209 debug("Writing to slave_fd")
210 os.write(slave_fd, TEST_STRING_1)
Cornelius Diekmanne6f62f62017-10-02 11:39:55 +0200211 s1 = _readline(master_fd)
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000212 self.assertEqual(b'I wish to buy a fish license.\n',
213 normalize_output(s1))
Neal Norwitz7d814522003-03-21 01:39:14 +0000214
Guido van Rossumd8faa362007-04-27 19:54:29 +0000215 debug("Writing chunked output")
216 os.write(slave_fd, TEST_STRING_2[:5])
217 os.write(slave_fd, TEST_STRING_2[5:])
Cornelius Diekmanne6f62f62017-10-02 11:39:55 +0200218 s2 = _readline(master_fd)
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000219 self.assertEqual(b'For my pet fish, Eric.\n', normalize_output(s2))
Neal Norwitz7d814522003-03-21 01:39:14 +0000220
Guido van Rossumd8faa362007-04-27 19:54:29 +0000221 os.close(slave_fd)
Victor Stinnera1838ec2019-12-09 11:57:05 +0100222 # closing master_fd can raise a SIGHUP if the process is
223 # the session leader: we installed a SIGHUP signal handler
224 # to ignore this signal.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000225 os.close(master_fd)
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000226
Guido van Rossumd8faa362007-04-27 19:54:29 +0000227 def test_fork(self):
228 debug("calling pty.fork()")
229 pid, master_fd = pty.fork()
230 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
308 os.close(master_fd)
309
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600310 def test_master_read(self):
311 debug("Calling pty.openpty()")
312 master_fd, slave_fd = pty.openpty()
313 debug(f"Got master_fd '{master_fd}', slave_fd '{slave_fd}'")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000314
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600315 debug("Closing slave_fd")
316 os.close(slave_fd)
317
318 debug("Reading from master_fd")
Soumendra Ganguly74311ae2020-11-28 15:04:20 -0600319 try:
320 data = os.read(master_fd, 1)
321 except OSError: # Linux
322 data = b""
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600323
324 os.close(master_fd)
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()