blob: a45be284a9544065ceb14dd8b6e75ad03a864a6f [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):
Soumendra Gangulyf5a19ea2020-11-27 04:16:41 -060077 # avoid isatty()
Soumendra Gangulyc13d8992020-11-25 07:41:25 -060078 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:
Soumendra Gangulyf5a19ea2020-11-27 04:16:41 -0600154 # Modify pty.STDIN_FILENO window size; we need to
155 # check if pty.openpty() is able to set pty slave
156 # window size accordingly.
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600157 debug("Setting pty.STDIN_FILENO window size")
Soumendra Gangulyf5a19ea2020-11-27 04:16:41 -0600158 debug(f"original size: (rows={self.stdin_rows}, cols={self.stdin_cols})")
159 target_stdin_rows = self.stdin_rows + 1
160 target_stdin_cols = self.stdin_cols + 1
161 debug(f"target size: (rows={target_stdin_rows}, cols={target_stdin_cols})")
162 target_stdin_winsz = struct.pack("HHHH", target_stdin_rows,
163 target_stdin_cols, 0, 0)
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600164 _set_term_winsz(pty.STDIN_FILENO, target_stdin_winsz)
165
166 # Were we able to set the window size
167 # of pty.STDIN_FILENO successfully?
168 new_stdin_winsz = _get_term_winsz(pty.STDIN_FILENO)
169 self.assertEqual(new_stdin_winsz, target_stdin_winsz,
170 "pty.STDIN_FILENO window size unchanged")
171 except OSError:
172 warnings.warn("Failed to set pty.STDIN_FILENO window size")
173 pass
174
175 try:
176 debug("Calling pty.openpty()")
177 try:
178 master_fd, slave_fd = pty.openpty(mode, new_stdin_winsz)
179 except TypeError:
180 master_fd, slave_fd = pty.openpty()
181 debug(f"Got master_fd '{master_fd}', slave_fd '{slave_fd}'")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000182 except OSError:
183 # " An optional feature could not be imported " ... ?
Benjamin Petersone549ead2009-03-28 21:42:05 +0000184 raise unittest.SkipTest("Pseudo-terminals (seemingly) not functional.")
Neal Norwitz7d814522003-03-21 01:39:14 +0000185
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600186 self.assertTrue(os.isatty(slave_fd), "slave_fd is not a tty")
187
188 if mode:
189 self.assertEqual(tty.tcgetattr(slave_fd), mode,
190 "openpty() failed to set slave termios")
191 if new_stdin_winsz:
192 self.assertEqual(_get_term_winsz(slave_fd), new_stdin_winsz,
193 "openpty() failed to set slave window size")
Neal Norwitz7d814522003-03-21 01:39:14 +0000194
Guido van Rossum360e4b82007-05-14 22:51:27 +0000195 # Solaris requires reading the fd before anything is returned.
196 # My guess is that since we open and close the slave fd
197 # in master_open(), we need to read the EOF.
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600198 #
199 # NOTE: the above comment is from an older version of the test;
200 # master_open() is not being used anymore.
Guido van Rossum360e4b82007-05-14 22:51:27 +0000201
202 # Ensure the fd is non-blocking in case there's nothing to read.
Victor Stinner1db9e7b2014-07-29 22:32:47 +0200203 blocking = os.get_blocking(master_fd)
Guido van Rossum360e4b82007-05-14 22:51:27 +0000204 try:
Victor Stinner1db9e7b2014-07-29 22:32:47 +0200205 os.set_blocking(master_fd, False)
206 try:
207 s1 = os.read(master_fd, 1024)
208 self.assertEqual(b'', s1)
209 except OSError as e:
210 if e.errno != errno.EAGAIN:
211 raise
212 finally:
213 # Restore the original flags.
214 os.set_blocking(master_fd, blocking)
Guido van Rossum360e4b82007-05-14 22:51:27 +0000215
Guido van Rossumd8faa362007-04-27 19:54:29 +0000216 debug("Writing to slave_fd")
217 os.write(slave_fd, TEST_STRING_1)
Cornelius Diekmanne6f62f62017-10-02 11:39:55 +0200218 s1 = _readline(master_fd)
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000219 self.assertEqual(b'I wish to buy a fish license.\n',
220 normalize_output(s1))
Neal Norwitz7d814522003-03-21 01:39:14 +0000221
Guido van Rossumd8faa362007-04-27 19:54:29 +0000222 debug("Writing chunked output")
223 os.write(slave_fd, TEST_STRING_2[:5])
224 os.write(slave_fd, TEST_STRING_2[5:])
Cornelius Diekmanne6f62f62017-10-02 11:39:55 +0200225 s2 = _readline(master_fd)
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000226 self.assertEqual(b'For my pet fish, Eric.\n', normalize_output(s2))
Neal Norwitz7d814522003-03-21 01:39:14 +0000227
Guido van Rossumd8faa362007-04-27 19:54:29 +0000228 os.close(slave_fd)
Victor Stinnera1838ec2019-12-09 11:57:05 +0100229 # closing master_fd can raise a SIGHUP if the process is
230 # the session leader: we installed a SIGHUP signal handler
231 # to ignore this signal.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000232 os.close(master_fd)
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000233
Guido van Rossumd8faa362007-04-27 19:54:29 +0000234 def test_fork(self):
235 debug("calling pty.fork()")
236 pid, master_fd = pty.fork()
237 if pid == pty.CHILD:
238 # stdout should be connected to a tty.
239 if not os.isatty(1):
240 debug("Child's fd 1 is not a tty?!")
241 os._exit(3)
Fred Drake4c136ee2000-06-30 23:22:35 +0000242
Guido van Rossumd8faa362007-04-27 19:54:29 +0000243 # After pty.fork(), the child should already be a session leader.
244 # (on those systems that have that concept.)
245 debug("In child, calling os.setsid()")
246 try:
247 os.setsid()
248 except OSError:
249 # Good, we already were session leader
250 debug("Good: OSError was raised.")
251 pass
252 except AttributeError:
253 # Have pty, but not setsid()?
254 debug("No setsid() available?")
255 pass
256 except:
257 # We don't want this error to propagate, escaping the call to
258 # os._exit() and causing very peculiar behavior in the calling
259 # regrtest.py !
260 # Note: could add traceback printing here.
261 debug("An unexpected error was raised.")
262 os._exit(1)
263 else:
264 debug("os.setsid() succeeded! (bad!)")
265 os._exit(2)
266 os._exit(4)
267 else:
268 debug("Waiting for child (%d) to finish." % pid)
269 # In verbose mode, we have to consume the debug output from the
270 # child or the child will block, causing this test to hang in the
271 # parent's waitpid() call. The child blocks after a
272 # platform-dependent amount of data is written to its fd. On
273 # Linux 2.6, it's 4000 bytes and the child won't block, but on OS
274 # X even the small writes in the child above will block it. Also
Andrew Svetlov737fb892012-12-18 21:14:22 +0200275 # on Linux, the read() will raise an OSError (input/output error)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000276 # when it tries to read past the end of the buffer but the child's
277 # already exited, so catch and discard those exceptions. It's not
278 # worth checking for EIO.
279 while True:
280 try:
281 data = os.read(master_fd, 80)
282 except OSError:
283 break
284 if not data:
285 break
Alexandre Vassalottia351f772008-03-03 02:59:49 +0000286 sys.stdout.write(str(data.replace(b'\r\n', b'\n'),
287 encoding='ascii'))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000288
289 ##line = os.read(master_fd, 80)
290 ##lines = line.replace('\r\n', '\n').split('\n')
291 ##if False and lines != ['In child, calling os.setsid()',
292 ## 'Good: OSError was raised.', '']:
293 ## raise TestFailed("Unexpected output from child: %r" % line)
294
295 (pid, status) = os.waitpid(pid, 0)
Victor Stinner65a796e2020-04-01 18:49:29 +0200296 res = os.waitstatus_to_exitcode(status)
297 debug("Child (%d) exited with code %d (status %d)." % (pid, res, status))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000298 if res == 1:
299 self.fail("Child raised an unexpected exception in os.setsid()")
300 elif res == 2:
301 self.fail("pty.fork() failed to make child a session leader.")
302 elif res == 3:
303 self.fail("Child spawned by pty.fork() did not have a tty as stdout")
304 elif res != 4:
305 self.fail("pty.fork() failed for unknown reasons.")
306
307 ##debug("Reading from master_fd now that the child has exited")
308 ##try:
309 ## s1 = os.read(master_fd, 1024)
Andrew Svetlov8b33dd82012-12-24 19:58:48 +0200310 ##except OSError:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000311 ## pass
312 ##else:
313 ## raise TestFailed("Read from master_fd did not raise exception")
314
315 os.close(master_fd)
316
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600317 @expectedFailureOnBSD
318 def test_master_read(self):
319 debug("Calling pty.openpty()")
320 master_fd, slave_fd = pty.openpty()
321 debug(f"Got master_fd '{master_fd}', slave_fd '{slave_fd}'")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000322
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600323 debug("Closing slave_fd")
324 os.close(slave_fd)
325
326 debug("Reading from master_fd")
327 with self.assertRaises(OSError):
328 os.read(master_fd, 1)
329
330 os.close(master_fd)
Gregory P. Smith05f59532012-02-16 00:29:12 -0800331
332class SmallPtyTests(unittest.TestCase):
333 """These tests don't spawn children or hang."""
334
335 def setUp(self):
336 self.orig_stdin_fileno = pty.STDIN_FILENO
337 self.orig_stdout_fileno = pty.STDOUT_FILENO
338 self.orig_pty_select = pty.select
339 self.fds = [] # A list of file descriptors to close.
Victor Stinnerb1f7f632012-03-06 02:04:58 +0100340 self.files = []
Gregory P. Smith05f59532012-02-16 00:29:12 -0800341 self.select_rfds_lengths = []
342 self.select_rfds_results = []
343
344 def tearDown(self):
345 pty.STDIN_FILENO = self.orig_stdin_fileno
346 pty.STDOUT_FILENO = self.orig_stdout_fileno
347 pty.select = self.orig_pty_select
Victor Stinnerb1f7f632012-03-06 02:04:58 +0100348 for file in self.files:
349 try:
350 file.close()
351 except OSError:
352 pass
Gregory P. Smith05f59532012-02-16 00:29:12 -0800353 for fd in self.fds:
354 try:
355 os.close(fd)
Victor Stinnerb1f7f632012-03-06 02:04:58 +0100356 except OSError:
Gregory P. Smith05f59532012-02-16 00:29:12 -0800357 pass
358
359 def _pipe(self):
360 pipe_fds = os.pipe()
361 self.fds.extend(pipe_fds)
362 return pipe_fds
363
Victor Stinnerb1f7f632012-03-06 02:04:58 +0100364 def _socketpair(self):
365 socketpair = socket.socketpair()
366 self.files.extend(socketpair)
367 return socketpair
368
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600369 def _mock_select(self, rfds, wfds, xfds, timeout=0):
Gregory P. Smith05f59532012-02-16 00:29:12 -0800370 # This will raise IndexError when no more expected calls exist.
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600371 # This ignores the timeout
Gregory P. Smith05f59532012-02-16 00:29:12 -0800372 self.assertEqual(self.select_rfds_lengths.pop(0), len(rfds))
373 return self.select_rfds_results.pop(0), [], []
374
375 def test__copy_to_each(self):
376 """Test the normal data case on both master_fd and stdin."""
377 read_from_stdout_fd, mock_stdout_fd = self._pipe()
378 pty.STDOUT_FILENO = mock_stdout_fd
379 mock_stdin_fd, write_to_stdin_fd = self._pipe()
380 pty.STDIN_FILENO = mock_stdin_fd
Victor Stinnerb1f7f632012-03-06 02:04:58 +0100381 socketpair = self._socketpair()
Gregory P. Smith05f59532012-02-16 00:29:12 -0800382 masters = [s.fileno() for s in socketpair]
Gregory P. Smith05f59532012-02-16 00:29:12 -0800383
384 # Feed data. Smaller than PIPEBUF. These writes will not block.
385 os.write(masters[1], b'from master')
386 os.write(write_to_stdin_fd, b'from stdin')
387
388 # Expect two select calls, the last one will cause IndexError
389 pty.select = self._mock_select
390 self.select_rfds_lengths.append(2)
391 self.select_rfds_results.append([mock_stdin_fd, masters[0]])
392 self.select_rfds_lengths.append(2)
393
394 with self.assertRaises(IndexError):
395 pty._copy(masters[0])
396
397 # Test that the right data went to the right places.
398 rfds = select.select([read_from_stdout_fd, masters[1]], [], [], 0)[0]
Gregory P. Smith5b791fb2012-02-16 00:35:43 -0800399 self.assertEqual([read_from_stdout_fd, masters[1]], rfds)
Gregory P. Smith05f59532012-02-16 00:29:12 -0800400 self.assertEqual(os.read(read_from_stdout_fd, 20), b'from master')
401 self.assertEqual(os.read(masters[1], 20), b'from stdin')
402
403 def test__copy_eof_on_all(self):
404 """Test the empty read EOF case on both master_fd and stdin."""
405 read_from_stdout_fd, mock_stdout_fd = self._pipe()
406 pty.STDOUT_FILENO = mock_stdout_fd
407 mock_stdin_fd, write_to_stdin_fd = self._pipe()
408 pty.STDIN_FILENO = mock_stdin_fd
Victor Stinnerb1f7f632012-03-06 02:04:58 +0100409 socketpair = self._socketpair()
Gregory P. Smith05f59532012-02-16 00:29:12 -0800410 masters = [s.fileno() for s in socketpair]
Gregory P. Smith05f59532012-02-16 00:29:12 -0800411
Gregory P. Smith05f59532012-02-16 00:29:12 -0800412 socketpair[1].close()
413 os.close(write_to_stdin_fd)
414
415 # Expect two select calls, the last one will cause IndexError
416 pty.select = self._mock_select
417 self.select_rfds_lengths.append(2)
418 self.select_rfds_results.append([mock_stdin_fd, masters[0]])
419 # We expect that both fds were removed from the fds list as they
420 # both encountered an EOF before the second select call.
421 self.select_rfds_lengths.append(0)
422
423 with self.assertRaises(IndexError):
424 pty._copy(masters[0])
425
426
Zachary Ware38c707e2015-04-13 15:00:43 -0500427def tearDownModule():
428 reap_children()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000429
430if __name__ == "__main__":
Zachary Ware38c707e2015-04-13 15:00:43 -0500431 unittest.main()