blob: 7de568806ed7d88bc6658959cde31739bccad8ce [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
20import platform
21import warnings
22
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000023TEST_STRING_1 = b"I wish to buy a fish license.\n"
24TEST_STRING_2 = b"For my pet fish, Eric.\n"
Fred Drake4c136ee2000-06-30 23:22:35 +000025
Soumendra Gangulyc13d8992020-11-25 07:41:25 -060026try:
27 _TIOCGWINSZ = tty.TIOCGWINSZ
28 _TIOCSWINSZ = tty.TIOCSWINSZ
29 _HAVE_WINSZ = True
30except AttributeError:
31 _HAVE_WINSZ = False
32
Fred Drake4c136ee2000-06-30 23:22:35 +000033if verbose:
34 def debug(msg):
Guido van Rossumbe19ed72007-02-09 05:37:30 +000035 print(msg)
Fred Drake4c136ee2000-06-30 23:22:35 +000036else:
37 def debug(msg):
38 pass
39
Guido van Rossumd8faa362007-04-27 19:54:29 +000040
Cornelius Diekmanne6f62f62017-10-02 11:39:55 +020041# Note that os.read() is nondeterministic so we need to be very careful
42# to make the test suite deterministic. A normal call to os.read() may
43# give us less than expected.
44#
45# Beware, on my Linux system, if I put 'foo\n' into a terminal fd, I get
46# back 'foo\r\n' at the other end. The behavior depends on the termios
47# setting. The newline translation may be OS-specific. To make the
48# test suite deterministic and OS-independent, the functions _readline
49# and normalize_output can be used.
50
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000051def normalize_output(data):
Benjamin Peterson06930632017-09-04 16:36:05 -070052 # Some operating systems do conversions on newline. We could possibly fix
53 # that by doing the appropriate termios.tcsetattr()s. I couldn't figure out
54 # the right combo on Tru64. So, just normalize the output and doc the
55 # problem O/Ses by allowing certain combinations for some platforms, but
56 # avoid allowing other differences (like extra whitespace, trailing garbage,
57 # etc.)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000058
59 # This is about the best we can do without getting some feedback
60 # from someone more knowledgable.
61
62 # OSF/1 (Tru64) apparently turns \n into \r\r\n.
Walter Dörwald812d8342007-05-29 18:57:42 +000063 if data.endswith(b'\r\r\n'):
64 return data.replace(b'\r\r\n', b'\n')
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000065
Walter Dörwald812d8342007-05-29 18:57:42 +000066 if data.endswith(b'\r\n'):
67 return data.replace(b'\r\n', b'\n')
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000068
69 return data
70
Cornelius Diekmanne6f62f62017-10-02 11:39:55 +020071def _readline(fd):
72 """Read one line. May block forever if no newline is read."""
73 reader = io.FileIO(fd, mode='rb', closefd=False)
74 return reader.readline()
75
Soumendra Gangulyc13d8992020-11-25 07:41:25 -060076def expectedFailureIfStdinIsTTY(fun):
77 # avoid isatty() for now
78 try:
79 tty.tcgetattr(pty.STDIN_FILENO)
80 return unittest.expectedFailure(fun)
81 except tty.error:
82 pass
83 return fun
84
85def expectedFailureOnBSD(fun):
86 PLATFORM = platform.system()
87 if PLATFORM.endswith("BSD") or PLATFORM == "Darwin":
88 return unittest.expectedFailure(fun)
89 return fun
90
91def _get_term_winsz(fd):
92 s = struct.pack("HHHH", 0, 0, 0, 0)
93 return fcntl.ioctl(fd, _TIOCGWINSZ, s)
94
95def _set_term_winsz(fd, winsz):
96 fcntl.ioctl(fd, _TIOCSWINSZ, winsz)
Cornelius Diekmanne6f62f62017-10-02 11:39:55 +020097
Guido van Rossumd8faa362007-04-27 19:54:29 +000098
Fred Drake4c136ee2000-06-30 23:22:35 +000099# Marginal testing of pty suite. Cannot do extensive 'do or fail' testing
100# because pty code is not too portable.
Guido van Rossum360e4b82007-05-14 22:51:27 +0000101# XXX(nnorwitz): these tests leak fds when there is an error.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000102class PtyTest(unittest.TestCase):
103 def setUp(self):
Victor Stinner9abee722017-09-19 09:36:54 -0700104 old_alarm = signal.signal(signal.SIGALRM, self.handle_sig)
105 self.addCleanup(signal.signal, signal.SIGALRM, old_alarm)
Victor Stinnera1838ec2019-12-09 11:57:05 +0100106
107 old_sighup = signal.signal(signal.SIGHUP, self.handle_sighup)
Victor Stinner7a51a7e2020-04-03 00:40:25 +0200108 self.addCleanup(signal.signal, signal.SIGHUP, old_sighup)
Victor Stinnera1838ec2019-12-09 11:57:05 +0100109
110 # isatty() and close() can hang on some platforms. Set an alarm
111 # before running the test to make sure we don't hang forever.
Victor Stinner9abee722017-09-19 09:36:54 -0700112 self.addCleanup(signal.alarm, 0)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000113 signal.alarm(10)
Fred Drake4c136ee2000-06-30 23:22:35 +0000114
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600115 # Save original stdin window size
116 self.stdin_rows = None
117 self.stdin_cols = None
118 if _HAVE_WINSZ:
119 try:
120 stdin_dim = os.get_terminal_size(pty.STDIN_FILENO)
121 self.stdin_rows = stdin_dim.lines
122 self.stdin_cols = stdin_dim.columns
123 old_stdin_winsz = struct.pack("HHHH", self.stdin_rows,
124 self.stdin_cols, 0, 0)
125 self.addCleanup(_set_term_winsz, pty.STDIN_FILENO, old_stdin_winsz)
126 except OSError:
127 pass
128
Guido van Rossumd8faa362007-04-27 19:54:29 +0000129 def handle_sig(self, sig, frame):
130 self.fail("isatty hung")
Neal Norwitz7d814522003-03-21 01:39:14 +0000131
Victor Stinnera1838ec2019-12-09 11:57:05 +0100132 @staticmethod
Victor Stinner7a51a7e2020-04-03 00:40:25 +0200133 def handle_sighup(signum, frame):
134 # bpo-38547: if the process is the session leader, os.close(master_fd)
Victor Stinnera1838ec2019-12-09 11:57:05 +0100135 # of "master_fd, slave_name = pty.master_open()" raises SIGHUP
136 # signal: just ignore the signal.
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600137 #
138 # NOTE: the above comment is from an older version of the test;
139 # master_open() is not being used anymore.
Victor Stinnera1838ec2019-12-09 11:57:05 +0100140 pass
141
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600142 @expectedFailureIfStdinIsTTY
143 def test_openpty(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000144 try:
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600145 mode = tty.tcgetattr(pty.STDIN_FILENO)
146 except tty.error:
147 # not a tty or bad/closed fd
148 debug("tty.tcgetattr(pty.STDIN_FILENO) failed")
149 mode = None
150
151 new_stdin_winsz = None
152 if self.stdin_rows != None and self.stdin_cols != None:
153 try:
154 debug("Setting pty.STDIN_FILENO window size")
155 # Set number of columns and rows to be the
156 # floors of 1/5 of respective original values
157 target_stdin_winsz = struct.pack("HHHH", self.stdin_rows//5,
158 self.stdin_cols//5, 0, 0)
159 _set_term_winsz(pty.STDIN_FILENO, target_stdin_winsz)
160
161 # Were we able to set the window size
162 # of pty.STDIN_FILENO successfully?
163 new_stdin_winsz = _get_term_winsz(pty.STDIN_FILENO)
164 self.assertEqual(new_stdin_winsz, target_stdin_winsz,
165 "pty.STDIN_FILENO window size unchanged")
166 except OSError:
167 warnings.warn("Failed to set pty.STDIN_FILENO window size")
168 pass
169
170 try:
171 debug("Calling pty.openpty()")
172 try:
173 master_fd, slave_fd = pty.openpty(mode, new_stdin_winsz)
174 except TypeError:
175 master_fd, slave_fd = pty.openpty()
176 debug(f"Got master_fd '{master_fd}', slave_fd '{slave_fd}'")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000177 except OSError:
178 # " An optional feature could not be imported " ... ?
Benjamin Petersone549ead2009-03-28 21:42:05 +0000179 raise unittest.SkipTest("Pseudo-terminals (seemingly) not functional.")
Neal Norwitz7d814522003-03-21 01:39:14 +0000180
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600181 self.assertTrue(os.isatty(slave_fd), "slave_fd is not a tty")
182
183 if mode:
184 self.assertEqual(tty.tcgetattr(slave_fd), mode,
185 "openpty() failed to set slave termios")
186 if new_stdin_winsz:
187 self.assertEqual(_get_term_winsz(slave_fd), new_stdin_winsz,
188 "openpty() failed to set slave window size")
Neal Norwitz7d814522003-03-21 01:39:14 +0000189
Guido van Rossum360e4b82007-05-14 22:51:27 +0000190 # Solaris requires reading the fd before anything is returned.
191 # My guess is that since we open and close the slave fd
192 # in master_open(), we need to read the EOF.
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600193 #
194 # NOTE: the above comment is from an older version of the test;
195 # master_open() is not being used anymore.
Guido van Rossum360e4b82007-05-14 22:51:27 +0000196
197 # Ensure the fd is non-blocking in case there's nothing to read.
Victor Stinner1db9e7b2014-07-29 22:32:47 +0200198 blocking = os.get_blocking(master_fd)
Guido van Rossum360e4b82007-05-14 22:51:27 +0000199 try:
Victor Stinner1db9e7b2014-07-29 22:32:47 +0200200 os.set_blocking(master_fd, False)
201 try:
202 s1 = os.read(master_fd, 1024)
203 self.assertEqual(b'', s1)
204 except OSError as e:
205 if e.errno != errno.EAGAIN:
206 raise
207 finally:
208 # Restore the original flags.
209 os.set_blocking(master_fd, blocking)
Guido van Rossum360e4b82007-05-14 22:51:27 +0000210
Guido van Rossumd8faa362007-04-27 19:54:29 +0000211 debug("Writing to slave_fd")
212 os.write(slave_fd, TEST_STRING_1)
Cornelius Diekmanne6f62f62017-10-02 11:39:55 +0200213 s1 = _readline(master_fd)
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000214 self.assertEqual(b'I wish to buy a fish license.\n',
215 normalize_output(s1))
Neal Norwitz7d814522003-03-21 01:39:14 +0000216
Guido van Rossumd8faa362007-04-27 19:54:29 +0000217 debug("Writing chunked output")
218 os.write(slave_fd, TEST_STRING_2[:5])
219 os.write(slave_fd, TEST_STRING_2[5:])
Cornelius Diekmanne6f62f62017-10-02 11:39:55 +0200220 s2 = _readline(master_fd)
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000221 self.assertEqual(b'For my pet fish, Eric.\n', normalize_output(s2))
Neal Norwitz7d814522003-03-21 01:39:14 +0000222
Guido van Rossumd8faa362007-04-27 19:54:29 +0000223 os.close(slave_fd)
Victor Stinnera1838ec2019-12-09 11:57:05 +0100224 # closing master_fd can raise a SIGHUP if the process is
225 # the session leader: we installed a SIGHUP signal handler
226 # to ignore this signal.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000227 os.close(master_fd)
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000228
Guido van Rossumd8faa362007-04-27 19:54:29 +0000229 def test_fork(self):
230 debug("calling pty.fork()")
231 pid, master_fd = pty.fork()
232 if pid == pty.CHILD:
233 # stdout should be connected to a tty.
234 if not os.isatty(1):
235 debug("Child's fd 1 is not a tty?!")
236 os._exit(3)
Fred Drake4c136ee2000-06-30 23:22:35 +0000237
Guido van Rossumd8faa362007-04-27 19:54:29 +0000238 # After pty.fork(), the child should already be a session leader.
239 # (on those systems that have that concept.)
240 debug("In child, calling os.setsid()")
241 try:
242 os.setsid()
243 except OSError:
244 # Good, we already were session leader
245 debug("Good: OSError was raised.")
246 pass
247 except AttributeError:
248 # Have pty, but not setsid()?
249 debug("No setsid() available?")
250 pass
251 except:
252 # We don't want this error to propagate, escaping the call to
253 # os._exit() and causing very peculiar behavior in the calling
254 # regrtest.py !
255 # Note: could add traceback printing here.
256 debug("An unexpected error was raised.")
257 os._exit(1)
258 else:
259 debug("os.setsid() succeeded! (bad!)")
260 os._exit(2)
261 os._exit(4)
262 else:
263 debug("Waiting for child (%d) to finish." % pid)
264 # In verbose mode, we have to consume the debug output from the
265 # child or the child will block, causing this test to hang in the
266 # parent's waitpid() call. The child blocks after a
267 # platform-dependent amount of data is written to its fd. On
268 # Linux 2.6, it's 4000 bytes and the child won't block, but on OS
269 # X even the small writes in the child above will block it. Also
Andrew Svetlov737fb892012-12-18 21:14:22 +0200270 # on Linux, the read() will raise an OSError (input/output error)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000271 # when it tries to read past the end of the buffer but the child's
272 # already exited, so catch and discard those exceptions. It's not
273 # worth checking for EIO.
274 while True:
275 try:
276 data = os.read(master_fd, 80)
277 except OSError:
278 break
279 if not data:
280 break
Alexandre Vassalottia351f772008-03-03 02:59:49 +0000281 sys.stdout.write(str(data.replace(b'\r\n', b'\n'),
282 encoding='ascii'))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000283
284 ##line = os.read(master_fd, 80)
285 ##lines = line.replace('\r\n', '\n').split('\n')
286 ##if False and lines != ['In child, calling os.setsid()',
287 ## 'Good: OSError was raised.', '']:
288 ## raise TestFailed("Unexpected output from child: %r" % line)
289
290 (pid, status) = os.waitpid(pid, 0)
Victor Stinner65a796e2020-04-01 18:49:29 +0200291 res = os.waitstatus_to_exitcode(status)
292 debug("Child (%d) exited with code %d (status %d)." % (pid, res, status))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000293 if res == 1:
294 self.fail("Child raised an unexpected exception in os.setsid()")
295 elif res == 2:
296 self.fail("pty.fork() failed to make child a session leader.")
297 elif res == 3:
298 self.fail("Child spawned by pty.fork() did not have a tty as stdout")
299 elif res != 4:
300 self.fail("pty.fork() failed for unknown reasons.")
301
302 ##debug("Reading from master_fd now that the child has exited")
303 ##try:
304 ## s1 = os.read(master_fd, 1024)
Andrew Svetlov8b33dd82012-12-24 19:58:48 +0200305 ##except OSError:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000306 ## pass
307 ##else:
308 ## raise TestFailed("Read from master_fd did not raise exception")
309
310 os.close(master_fd)
311
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600312 @expectedFailureOnBSD
313 def test_master_read(self):
314 debug("Calling pty.openpty()")
315 master_fd, slave_fd = pty.openpty()
316 debug(f"Got master_fd '{master_fd}', slave_fd '{slave_fd}'")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000317
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600318 debug("Closing slave_fd")
319 os.close(slave_fd)
320
321 debug("Reading from master_fd")
322 with self.assertRaises(OSError):
323 os.read(master_fd, 1)
324
325 os.close(master_fd)
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()