blob: 138560e0309ab055c06fd48f3c3853d6d5f08a45 [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
Andrew Svetlov87f7ab52020-11-25 19:06:12 +02008import pathlib
R. David Murrayeb3615d2009-04-22 02:24:39 +00009import pty
Guido van Rossumd8faa362007-04-27 19:54:29 +000010import os
11import sys
Gregory P. Smith05f59532012-02-16 00:29:12 -080012import select
Guido van Rossumd8faa362007-04-27 19:54:29 +000013import signal
Gregory P. Smith05f59532012-02-16 00:29:12 -080014import socket
Cornelius Diekmanne6f62f62017-10-02 11:39:55 +020015import io # readline
Guido van Rossumd8faa362007-04-27 19:54:29 +000016import unittest
Fred Drake4c136ee2000-06-30 23:22:35 +000017
Soumendra Gangulyc13d8992020-11-25 07:41:25 -060018import struct
19import tty
20import fcntl
21import platform
22import warnings
23
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000024TEST_STRING_1 = b"I wish to buy a fish license.\n"
25TEST_STRING_2 = b"For my pet fish, Eric.\n"
Fred Drake4c136ee2000-06-30 23:22:35 +000026
Soumendra Gangulyc13d8992020-11-25 07:41:25 -060027try:
28 _TIOCGWINSZ = tty.TIOCGWINSZ
29 _TIOCSWINSZ = tty.TIOCSWINSZ
30 _HAVE_WINSZ = True
31except AttributeError:
32 _HAVE_WINSZ = False
33
Fred Drake4c136ee2000-06-30 23:22:35 +000034if verbose:
35 def debug(msg):
Guido van Rossumbe19ed72007-02-09 05:37:30 +000036 print(msg)
Fred Drake4c136ee2000-06-30 23:22:35 +000037else:
38 def debug(msg):
39 pass
40
Guido van Rossumd8faa362007-04-27 19:54:29 +000041
Cornelius Diekmanne6f62f62017-10-02 11:39:55 +020042# Note that os.read() is nondeterministic so we need to be very careful
43# to make the test suite deterministic. A normal call to os.read() may
44# give us less than expected.
45#
46# Beware, on my Linux system, if I put 'foo\n' into a terminal fd, I get
47# back 'foo\r\n' at the other end. The behavior depends on the termios
48# setting. The newline translation may be OS-specific. To make the
49# test suite deterministic and OS-independent, the functions _readline
50# and normalize_output can be used.
51
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000052def normalize_output(data):
Benjamin Peterson06930632017-09-04 16:36:05 -070053 # Some operating systems do conversions on newline. We could possibly fix
54 # that by doing the appropriate termios.tcsetattr()s. I couldn't figure out
55 # the right combo on Tru64. So, just normalize the output and doc the
56 # problem O/Ses by allowing certain combinations for some platforms, but
57 # avoid allowing other differences (like extra whitespace, trailing garbage,
58 # etc.)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000059
60 # This is about the best we can do without getting some feedback
61 # from someone more knowledgable.
62
63 # OSF/1 (Tru64) apparently turns \n into \r\r\n.
Walter Dörwald812d8342007-05-29 18:57:42 +000064 if data.endswith(b'\r\r\n'):
65 return data.replace(b'\r\r\n', b'\n')
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000066
Walter Dörwald812d8342007-05-29 18:57:42 +000067 if data.endswith(b'\r\n'):
68 return data.replace(b'\r\n', b'\n')
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000069
70 return data
71
Cornelius Diekmanne6f62f62017-10-02 11:39:55 +020072def _readline(fd):
73 """Read one line. May block forever if no newline is read."""
74 reader = io.FileIO(fd, mode='rb', closefd=False)
75 return reader.readline()
76
Soumendra Gangulyc13d8992020-11-25 07:41:25 -060077def expectedFailureIfStdinIsTTY(fun):
78 # avoid isatty() for now
Andrew Svetlov87f7ab52020-11-25 19:06:12 +020079 PLATFORM = platform.system()
80 if PLATFORM == "Linux":
81 os_release = pathlib.Path("/etc/os-release")
82 if os_release.exists():
83 # Actually the file has complex multi-line structure,
84 # these is no need to parse it for Gentoo check
85 if 'gentoo' in os_release.read_text().lower():
86 # bpo-41818:
87 # Gentoo passes the test,
88 # all other tested Linux distributions fail.
89 # Should not apply @unittest.expectedFailure() on Gentoo
90 # to keep the buildbot fleet happy.
91 return fun
Soumendra Gangulyc13d8992020-11-25 07:41:25 -060092 try:
93 tty.tcgetattr(pty.STDIN_FILENO)
94 return unittest.expectedFailure(fun)
95 except tty.error:
96 pass
97 return fun
98
99def expectedFailureOnBSD(fun):
100 PLATFORM = platform.system()
101 if PLATFORM.endswith("BSD") or PLATFORM == "Darwin":
102 return unittest.expectedFailure(fun)
103 return fun
104
105def _get_term_winsz(fd):
106 s = struct.pack("HHHH", 0, 0, 0, 0)
107 return fcntl.ioctl(fd, _TIOCGWINSZ, s)
108
109def _set_term_winsz(fd, winsz):
110 fcntl.ioctl(fd, _TIOCSWINSZ, winsz)
Cornelius Diekmanne6f62f62017-10-02 11:39:55 +0200111
Guido van Rossumd8faa362007-04-27 19:54:29 +0000112
Fred Drake4c136ee2000-06-30 23:22:35 +0000113# Marginal testing of pty suite. Cannot do extensive 'do or fail' testing
114# because pty code is not too portable.
Guido van Rossum360e4b82007-05-14 22:51:27 +0000115# XXX(nnorwitz): these tests leak fds when there is an error.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000116class PtyTest(unittest.TestCase):
117 def setUp(self):
Victor Stinner9abee722017-09-19 09:36:54 -0700118 old_alarm = signal.signal(signal.SIGALRM, self.handle_sig)
119 self.addCleanup(signal.signal, signal.SIGALRM, old_alarm)
Victor Stinnera1838ec2019-12-09 11:57:05 +0100120
121 old_sighup = signal.signal(signal.SIGHUP, self.handle_sighup)
Victor Stinner7a51a7e2020-04-03 00:40:25 +0200122 self.addCleanup(signal.signal, signal.SIGHUP, old_sighup)
Victor Stinnera1838ec2019-12-09 11:57:05 +0100123
124 # isatty() and close() can hang on some platforms. Set an alarm
125 # before running the test to make sure we don't hang forever.
Victor Stinner9abee722017-09-19 09:36:54 -0700126 self.addCleanup(signal.alarm, 0)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000127 signal.alarm(10)
Fred Drake4c136ee2000-06-30 23:22:35 +0000128
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600129 # Save original stdin window size
130 self.stdin_rows = None
131 self.stdin_cols = None
132 if _HAVE_WINSZ:
133 try:
134 stdin_dim = os.get_terminal_size(pty.STDIN_FILENO)
135 self.stdin_rows = stdin_dim.lines
136 self.stdin_cols = stdin_dim.columns
137 old_stdin_winsz = struct.pack("HHHH", self.stdin_rows,
138 self.stdin_cols, 0, 0)
139 self.addCleanup(_set_term_winsz, pty.STDIN_FILENO, old_stdin_winsz)
140 except OSError:
141 pass
142
Guido van Rossumd8faa362007-04-27 19:54:29 +0000143 def handle_sig(self, sig, frame):
144 self.fail("isatty hung")
Neal Norwitz7d814522003-03-21 01:39:14 +0000145
Victor Stinnera1838ec2019-12-09 11:57:05 +0100146 @staticmethod
Victor Stinner7a51a7e2020-04-03 00:40:25 +0200147 def handle_sighup(signum, frame):
148 # bpo-38547: if the process is the session leader, os.close(master_fd)
Victor Stinnera1838ec2019-12-09 11:57:05 +0100149 # of "master_fd, slave_name = pty.master_open()" raises SIGHUP
150 # signal: just ignore the signal.
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600151 #
152 # NOTE: the above comment is from an older version of the test;
153 # master_open() is not being used anymore.
Victor Stinnera1838ec2019-12-09 11:57:05 +0100154 pass
155
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600156 @expectedFailureIfStdinIsTTY
157 def test_openpty(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000158 try:
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600159 mode = tty.tcgetattr(pty.STDIN_FILENO)
160 except tty.error:
161 # not a tty or bad/closed fd
162 debug("tty.tcgetattr(pty.STDIN_FILENO) failed")
163 mode = None
164
165 new_stdin_winsz = None
166 if self.stdin_rows != None and self.stdin_cols != None:
167 try:
168 debug("Setting pty.STDIN_FILENO window size")
169 # Set number of columns and rows to be the
170 # floors of 1/5 of respective original values
171 target_stdin_winsz = struct.pack("HHHH", self.stdin_rows//5,
172 self.stdin_cols//5, 0, 0)
173 _set_term_winsz(pty.STDIN_FILENO, target_stdin_winsz)
174
175 # Were we able to set the window size
176 # of pty.STDIN_FILENO successfully?
177 new_stdin_winsz = _get_term_winsz(pty.STDIN_FILENO)
178 self.assertEqual(new_stdin_winsz, target_stdin_winsz,
179 "pty.STDIN_FILENO window size unchanged")
180 except OSError:
181 warnings.warn("Failed to set pty.STDIN_FILENO window size")
182 pass
183
184 try:
185 debug("Calling pty.openpty()")
186 try:
187 master_fd, slave_fd = pty.openpty(mode, new_stdin_winsz)
188 except TypeError:
189 master_fd, slave_fd = pty.openpty()
190 debug(f"Got master_fd '{master_fd}', slave_fd '{slave_fd}'")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000191 except OSError:
192 # " An optional feature could not be imported " ... ?
Benjamin Petersone549ead2009-03-28 21:42:05 +0000193 raise unittest.SkipTest("Pseudo-terminals (seemingly) not functional.")
Neal Norwitz7d814522003-03-21 01:39:14 +0000194
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600195 self.assertTrue(os.isatty(slave_fd), "slave_fd is not a tty")
196
197 if mode:
198 self.assertEqual(tty.tcgetattr(slave_fd), mode,
199 "openpty() failed to set slave termios")
200 if new_stdin_winsz:
201 self.assertEqual(_get_term_winsz(slave_fd), new_stdin_winsz,
202 "openpty() failed to set slave window size")
Neal Norwitz7d814522003-03-21 01:39:14 +0000203
Guido van Rossum360e4b82007-05-14 22:51:27 +0000204 # Solaris requires reading the fd before anything is returned.
205 # My guess is that since we open and close the slave fd
206 # in master_open(), we need to read the EOF.
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600207 #
208 # NOTE: the above comment is from an older version of the test;
209 # master_open() is not being used anymore.
Guido van Rossum360e4b82007-05-14 22:51:27 +0000210
211 # Ensure the fd is non-blocking in case there's nothing to read.
Victor Stinner1db9e7b2014-07-29 22:32:47 +0200212 blocking = os.get_blocking(master_fd)
Guido van Rossum360e4b82007-05-14 22:51:27 +0000213 try:
Victor Stinner1db9e7b2014-07-29 22:32:47 +0200214 os.set_blocking(master_fd, False)
215 try:
216 s1 = os.read(master_fd, 1024)
217 self.assertEqual(b'', s1)
218 except OSError as e:
219 if e.errno != errno.EAGAIN:
220 raise
221 finally:
222 # Restore the original flags.
223 os.set_blocking(master_fd, blocking)
Guido van Rossum360e4b82007-05-14 22:51:27 +0000224
Guido van Rossumd8faa362007-04-27 19:54:29 +0000225 debug("Writing to slave_fd")
226 os.write(slave_fd, TEST_STRING_1)
Cornelius Diekmanne6f62f62017-10-02 11:39:55 +0200227 s1 = _readline(master_fd)
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000228 self.assertEqual(b'I wish to buy a fish license.\n',
229 normalize_output(s1))
Neal Norwitz7d814522003-03-21 01:39:14 +0000230
Guido van Rossumd8faa362007-04-27 19:54:29 +0000231 debug("Writing chunked output")
232 os.write(slave_fd, TEST_STRING_2[:5])
233 os.write(slave_fd, TEST_STRING_2[5:])
Cornelius Diekmanne6f62f62017-10-02 11:39:55 +0200234 s2 = _readline(master_fd)
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000235 self.assertEqual(b'For my pet fish, Eric.\n', normalize_output(s2))
Neal Norwitz7d814522003-03-21 01:39:14 +0000236
Guido van Rossumd8faa362007-04-27 19:54:29 +0000237 os.close(slave_fd)
Victor Stinnera1838ec2019-12-09 11:57:05 +0100238 # closing master_fd can raise a SIGHUP if the process is
239 # the session leader: we installed a SIGHUP signal handler
240 # to ignore this signal.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000241 os.close(master_fd)
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000242
Guido van Rossumd8faa362007-04-27 19:54:29 +0000243 def test_fork(self):
244 debug("calling pty.fork()")
245 pid, master_fd = pty.fork()
246 if pid == pty.CHILD:
247 # stdout should be connected to a tty.
248 if not os.isatty(1):
249 debug("Child's fd 1 is not a tty?!")
250 os._exit(3)
Fred Drake4c136ee2000-06-30 23:22:35 +0000251
Guido van Rossumd8faa362007-04-27 19:54:29 +0000252 # After pty.fork(), the child should already be a session leader.
253 # (on those systems that have that concept.)
254 debug("In child, calling os.setsid()")
255 try:
256 os.setsid()
257 except OSError:
258 # Good, we already were session leader
259 debug("Good: OSError was raised.")
260 pass
261 except AttributeError:
262 # Have pty, but not setsid()?
263 debug("No setsid() available?")
264 pass
265 except:
266 # We don't want this error to propagate, escaping the call to
267 # os._exit() and causing very peculiar behavior in the calling
268 # regrtest.py !
269 # Note: could add traceback printing here.
270 debug("An unexpected error was raised.")
271 os._exit(1)
272 else:
273 debug("os.setsid() succeeded! (bad!)")
274 os._exit(2)
275 os._exit(4)
276 else:
277 debug("Waiting for child (%d) to finish." % pid)
278 # In verbose mode, we have to consume the debug output from the
279 # child or the child will block, causing this test to hang in the
280 # parent's waitpid() call. The child blocks after a
281 # platform-dependent amount of data is written to its fd. On
282 # Linux 2.6, it's 4000 bytes and the child won't block, but on OS
283 # X even the small writes in the child above will block it. Also
Andrew Svetlov737fb892012-12-18 21:14:22 +0200284 # on Linux, the read() will raise an OSError (input/output error)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000285 # when it tries to read past the end of the buffer but the child's
286 # already exited, so catch and discard those exceptions. It's not
287 # worth checking for EIO.
288 while True:
289 try:
290 data = os.read(master_fd, 80)
291 except OSError:
292 break
293 if not data:
294 break
Alexandre Vassalottia351f772008-03-03 02:59:49 +0000295 sys.stdout.write(str(data.replace(b'\r\n', b'\n'),
296 encoding='ascii'))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000297
298 ##line = os.read(master_fd, 80)
299 ##lines = line.replace('\r\n', '\n').split('\n')
300 ##if False and lines != ['In child, calling os.setsid()',
301 ## 'Good: OSError was raised.', '']:
302 ## raise TestFailed("Unexpected output from child: %r" % line)
303
304 (pid, status) = os.waitpid(pid, 0)
Victor Stinner65a796e2020-04-01 18:49:29 +0200305 res = os.waitstatus_to_exitcode(status)
306 debug("Child (%d) exited with code %d (status %d)." % (pid, res, status))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000307 if res == 1:
308 self.fail("Child raised an unexpected exception in os.setsid()")
309 elif res == 2:
310 self.fail("pty.fork() failed to make child a session leader.")
311 elif res == 3:
312 self.fail("Child spawned by pty.fork() did not have a tty as stdout")
313 elif res != 4:
314 self.fail("pty.fork() failed for unknown reasons.")
315
316 ##debug("Reading from master_fd now that the child has exited")
317 ##try:
318 ## s1 = os.read(master_fd, 1024)
Andrew Svetlov8b33dd82012-12-24 19:58:48 +0200319 ##except OSError:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000320 ## pass
321 ##else:
322 ## raise TestFailed("Read from master_fd did not raise exception")
323
324 os.close(master_fd)
325
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600326 @expectedFailureOnBSD
327 def test_master_read(self):
328 debug("Calling pty.openpty()")
329 master_fd, slave_fd = pty.openpty()
330 debug(f"Got master_fd '{master_fd}', slave_fd '{slave_fd}'")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000331
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600332 debug("Closing slave_fd")
333 os.close(slave_fd)
334
335 debug("Reading from master_fd")
336 with self.assertRaises(OSError):
337 os.read(master_fd, 1)
338
339 os.close(master_fd)
Gregory P. Smith05f59532012-02-16 00:29:12 -0800340
341class SmallPtyTests(unittest.TestCase):
342 """These tests don't spawn children or hang."""
343
344 def setUp(self):
345 self.orig_stdin_fileno = pty.STDIN_FILENO
346 self.orig_stdout_fileno = pty.STDOUT_FILENO
347 self.orig_pty_select = pty.select
348 self.fds = [] # A list of file descriptors to close.
Victor Stinnerb1f7f632012-03-06 02:04:58 +0100349 self.files = []
Gregory P. Smith05f59532012-02-16 00:29:12 -0800350 self.select_rfds_lengths = []
351 self.select_rfds_results = []
352
353 def tearDown(self):
354 pty.STDIN_FILENO = self.orig_stdin_fileno
355 pty.STDOUT_FILENO = self.orig_stdout_fileno
356 pty.select = self.orig_pty_select
Victor Stinnerb1f7f632012-03-06 02:04:58 +0100357 for file in self.files:
358 try:
359 file.close()
360 except OSError:
361 pass
Gregory P. Smith05f59532012-02-16 00:29:12 -0800362 for fd in self.fds:
363 try:
364 os.close(fd)
Victor Stinnerb1f7f632012-03-06 02:04:58 +0100365 except OSError:
Gregory P. Smith05f59532012-02-16 00:29:12 -0800366 pass
367
368 def _pipe(self):
369 pipe_fds = os.pipe()
370 self.fds.extend(pipe_fds)
371 return pipe_fds
372
Victor Stinnerb1f7f632012-03-06 02:04:58 +0100373 def _socketpair(self):
374 socketpair = socket.socketpair()
375 self.files.extend(socketpair)
376 return socketpair
377
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600378 def _mock_select(self, rfds, wfds, xfds, timeout=0):
Gregory P. Smith05f59532012-02-16 00:29:12 -0800379 # This will raise IndexError when no more expected calls exist.
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600380 # This ignores the timeout
Gregory P. Smith05f59532012-02-16 00:29:12 -0800381 self.assertEqual(self.select_rfds_lengths.pop(0), len(rfds))
382 return self.select_rfds_results.pop(0), [], []
383
384 def test__copy_to_each(self):
385 """Test the normal data case on both master_fd and stdin."""
386 read_from_stdout_fd, mock_stdout_fd = self._pipe()
387 pty.STDOUT_FILENO = mock_stdout_fd
388 mock_stdin_fd, write_to_stdin_fd = self._pipe()
389 pty.STDIN_FILENO = mock_stdin_fd
Victor Stinnerb1f7f632012-03-06 02:04:58 +0100390 socketpair = self._socketpair()
Gregory P. Smith05f59532012-02-16 00:29:12 -0800391 masters = [s.fileno() for s in socketpair]
Gregory P. Smith05f59532012-02-16 00:29:12 -0800392
393 # Feed data. Smaller than PIPEBUF. These writes will not block.
394 os.write(masters[1], b'from master')
395 os.write(write_to_stdin_fd, b'from stdin')
396
397 # Expect two select calls, the last one will cause IndexError
398 pty.select = self._mock_select
399 self.select_rfds_lengths.append(2)
400 self.select_rfds_results.append([mock_stdin_fd, masters[0]])
401 self.select_rfds_lengths.append(2)
402
403 with self.assertRaises(IndexError):
404 pty._copy(masters[0])
405
406 # Test that the right data went to the right places.
407 rfds = select.select([read_from_stdout_fd, masters[1]], [], [], 0)[0]
Gregory P. Smith5b791fb2012-02-16 00:35:43 -0800408 self.assertEqual([read_from_stdout_fd, masters[1]], rfds)
Gregory P. Smith05f59532012-02-16 00:29:12 -0800409 self.assertEqual(os.read(read_from_stdout_fd, 20), b'from master')
410 self.assertEqual(os.read(masters[1], 20), b'from stdin')
411
412 def test__copy_eof_on_all(self):
413 """Test the empty read EOF case on both master_fd and stdin."""
414 read_from_stdout_fd, mock_stdout_fd = self._pipe()
415 pty.STDOUT_FILENO = mock_stdout_fd
416 mock_stdin_fd, write_to_stdin_fd = self._pipe()
417 pty.STDIN_FILENO = mock_stdin_fd
Victor Stinnerb1f7f632012-03-06 02:04:58 +0100418 socketpair = self._socketpair()
Gregory P. Smith05f59532012-02-16 00:29:12 -0800419 masters = [s.fileno() for s in socketpair]
Gregory P. Smith05f59532012-02-16 00:29:12 -0800420
Gregory P. Smith05f59532012-02-16 00:29:12 -0800421 socketpair[1].close()
422 os.close(write_to_stdin_fd)
423
424 # Expect two select calls, the last one will cause IndexError
425 pty.select = self._mock_select
426 self.select_rfds_lengths.append(2)
427 self.select_rfds_results.append([mock_stdin_fd, masters[0]])
428 # We expect that both fds were removed from the fds list as they
429 # both encountered an EOF before the second select call.
430 self.select_rfds_lengths.append(0)
431
432 with self.assertRaises(IndexError):
433 pty._copy(masters[0])
434
435
Zachary Ware38c707e2015-04-13 15:00:43 -0500436def tearDownModule():
437 reap_children()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000438
439if __name__ == "__main__":
Zachary Ware38c707e2015-04-13 15:00:43 -0500440 unittest.main()