blob: 0c178127571b07c8310de09c52306b2ea8da5466 [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
Guido van Rossumd8faa362007-04-27 19:54:29 +00008import os
Miss Islington (bot)5d444432021-08-12 05:36:04 -07009import pty
10import tty
Guido van Rossumd8faa362007-04-27 19:54:29 +000011import 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
Soumendra Gangulyc13d8992020-11-25 07:41:25 -060021import 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
Soumendra Gangulyc13d8992020-11-25 07:41:25 -060085def _get_term_winsz(fd):
86 s = struct.pack("HHHH", 0, 0, 0, 0)
87 return fcntl.ioctl(fd, _TIOCGWINSZ, s)
88
89def _set_term_winsz(fd, winsz):
90 fcntl.ioctl(fd, _TIOCSWINSZ, winsz)
Cornelius Diekmanne6f62f62017-10-02 11:39:55 +020091
Guido van Rossumd8faa362007-04-27 19:54:29 +000092
Fred Drake4c136ee2000-06-30 23:22:35 +000093# Marginal testing of pty suite. Cannot do extensive 'do or fail' testing
94# because pty code is not too portable.
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):
Victor Stinnera1838ec2019-12-09 11:57:05 +0100127 pass
128
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600129 @expectedFailureIfStdinIsTTY
130 def test_openpty(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000131 try:
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600132 mode = tty.tcgetattr(pty.STDIN_FILENO)
133 except tty.error:
134 # not a tty or bad/closed fd
135 debug("tty.tcgetattr(pty.STDIN_FILENO) failed")
136 mode = None
137
138 new_stdin_winsz = None
Serhiy Storchakae2b29302021-09-04 04:13:00 +0300139 if self.stdin_rows is not None and self.stdin_cols is not None:
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600140 try:
Soumendra Gangulyf5a19ea2020-11-27 04:16:41 -0600141 # Modify pty.STDIN_FILENO window size; we need to
142 # check if pty.openpty() is able to set pty slave
143 # window size accordingly.
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600144 debug("Setting pty.STDIN_FILENO window size")
Soumendra Gangulyf5a19ea2020-11-27 04:16:41 -0600145 debug(f"original size: (rows={self.stdin_rows}, cols={self.stdin_cols})")
146 target_stdin_rows = self.stdin_rows + 1
147 target_stdin_cols = self.stdin_cols + 1
148 debug(f"target size: (rows={target_stdin_rows}, cols={target_stdin_cols})")
149 target_stdin_winsz = struct.pack("HHHH", target_stdin_rows,
150 target_stdin_cols, 0, 0)
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600151 _set_term_winsz(pty.STDIN_FILENO, target_stdin_winsz)
152
153 # Were we able to set the window size
154 # of pty.STDIN_FILENO successfully?
155 new_stdin_winsz = _get_term_winsz(pty.STDIN_FILENO)
156 self.assertEqual(new_stdin_winsz, target_stdin_winsz,
157 "pty.STDIN_FILENO window size unchanged")
158 except OSError:
159 warnings.warn("Failed to set pty.STDIN_FILENO window size")
160 pass
161
162 try:
163 debug("Calling pty.openpty()")
164 try:
165 master_fd, slave_fd = pty.openpty(mode, new_stdin_winsz)
166 except TypeError:
167 master_fd, slave_fd = pty.openpty()
168 debug(f"Got master_fd '{master_fd}', slave_fd '{slave_fd}'")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000169 except OSError:
170 # " An optional feature could not be imported " ... ?
Benjamin Petersone549ead2009-03-28 21:42:05 +0000171 raise unittest.SkipTest("Pseudo-terminals (seemingly) not functional.")
Neal Norwitz7d814522003-03-21 01:39:14 +0000172
Petr Viktorin65cf1ad2021-01-19 14:03:12 +0100173 # closing master_fd can raise a SIGHUP if the process is
174 # the session leader: we installed a SIGHUP signal handler
175 # to ignore this signal.
176 self.addCleanup(os.close, master_fd)
177 self.addCleanup(os.close, slave_fd)
178
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 # Ensure the fd is non-blocking in case there's nothing to read.
Victor Stinner1db9e7b2014-07-29 22:32:47 +0200189 blocking = os.get_blocking(master_fd)
Guido van Rossum360e4b82007-05-14 22:51:27 +0000190 try:
Victor Stinner1db9e7b2014-07-29 22:32:47 +0200191 os.set_blocking(master_fd, False)
192 try:
193 s1 = os.read(master_fd, 1024)
194 self.assertEqual(b'', s1)
195 except OSError as e:
196 if e.errno != errno.EAGAIN:
197 raise
198 finally:
199 # Restore the original flags.
200 os.set_blocking(master_fd, blocking)
Guido van Rossum360e4b82007-05-14 22:51:27 +0000201
Guido van Rossumd8faa362007-04-27 19:54:29 +0000202 debug("Writing to slave_fd")
203 os.write(slave_fd, TEST_STRING_1)
Cornelius Diekmanne6f62f62017-10-02 11:39:55 +0200204 s1 = _readline(master_fd)
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000205 self.assertEqual(b'I wish to buy a fish license.\n',
206 normalize_output(s1))
Neal Norwitz7d814522003-03-21 01:39:14 +0000207
Guido van Rossumd8faa362007-04-27 19:54:29 +0000208 debug("Writing chunked output")
209 os.write(slave_fd, TEST_STRING_2[:5])
210 os.write(slave_fd, TEST_STRING_2[5:])
Cornelius Diekmanne6f62f62017-10-02 11:39:55 +0200211 s2 = _readline(master_fd)
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000212 self.assertEqual(b'For my pet fish, Eric.\n', normalize_output(s2))
Neal Norwitz7d814522003-03-21 01:39:14 +0000213
Guido van Rossumd8faa362007-04-27 19:54:29 +0000214 def test_fork(self):
215 debug("calling pty.fork()")
216 pid, master_fd = pty.fork()
Petr Viktorin65cf1ad2021-01-19 14:03:12 +0100217 self.addCleanup(os.close, master_fd)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000218 if pid == pty.CHILD:
219 # stdout should be connected to a tty.
220 if not os.isatty(1):
221 debug("Child's fd 1 is not a tty?!")
222 os._exit(3)
Fred Drake4c136ee2000-06-30 23:22:35 +0000223
Guido van Rossumd8faa362007-04-27 19:54:29 +0000224 # After pty.fork(), the child should already be a session leader.
225 # (on those systems that have that concept.)
226 debug("In child, calling os.setsid()")
227 try:
228 os.setsid()
229 except OSError:
230 # Good, we already were session leader
231 debug("Good: OSError was raised.")
232 pass
233 except AttributeError:
234 # Have pty, but not setsid()?
235 debug("No setsid() available?")
236 pass
237 except:
238 # We don't want this error to propagate, escaping the call to
239 # os._exit() and causing very peculiar behavior in the calling
240 # regrtest.py !
241 # Note: could add traceback printing here.
242 debug("An unexpected error was raised.")
243 os._exit(1)
244 else:
245 debug("os.setsid() succeeded! (bad!)")
246 os._exit(2)
247 os._exit(4)
248 else:
249 debug("Waiting for child (%d) to finish." % pid)
250 # In verbose mode, we have to consume the debug output from the
251 # child or the child will block, causing this test to hang in the
252 # parent's waitpid() call. The child blocks after a
253 # platform-dependent amount of data is written to its fd. On
254 # Linux 2.6, it's 4000 bytes and the child won't block, but on OS
255 # X even the small writes in the child above will block it. Also
Andrew Svetlov737fb892012-12-18 21:14:22 +0200256 # on Linux, the read() will raise an OSError (input/output error)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000257 # when it tries to read past the end of the buffer but the child's
258 # already exited, so catch and discard those exceptions. It's not
259 # worth checking for EIO.
260 while True:
261 try:
262 data = os.read(master_fd, 80)
263 except OSError:
264 break
265 if not data:
266 break
Alexandre Vassalottia351f772008-03-03 02:59:49 +0000267 sys.stdout.write(str(data.replace(b'\r\n', b'\n'),
268 encoding='ascii'))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000269
270 ##line = os.read(master_fd, 80)
271 ##lines = line.replace('\r\n', '\n').split('\n')
272 ##if False and lines != ['In child, calling os.setsid()',
273 ## 'Good: OSError was raised.', '']:
274 ## raise TestFailed("Unexpected output from child: %r" % line)
275
276 (pid, status) = os.waitpid(pid, 0)
Victor Stinner65a796e2020-04-01 18:49:29 +0200277 res = os.waitstatus_to_exitcode(status)
278 debug("Child (%d) exited with code %d (status %d)." % (pid, res, status))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000279 if res == 1:
280 self.fail("Child raised an unexpected exception in os.setsid()")
281 elif res == 2:
282 self.fail("pty.fork() failed to make child a session leader.")
283 elif res == 3:
284 self.fail("Child spawned by pty.fork() did not have a tty as stdout")
285 elif res != 4:
286 self.fail("pty.fork() failed for unknown reasons.")
287
288 ##debug("Reading from master_fd now that the child has exited")
289 ##try:
290 ## s1 = os.read(master_fd, 1024)
Andrew Svetlov8b33dd82012-12-24 19:58:48 +0200291 ##except OSError:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000292 ## pass
293 ##else:
294 ## raise TestFailed("Read from master_fd did not raise exception")
295
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600296 def test_master_read(self):
Petr Viktorin65cf1ad2021-01-19 14:03:12 +0100297 # XXX(nnorwitz): this test leaks fds when there is an error.
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600298 debug("Calling pty.openpty()")
299 master_fd, slave_fd = pty.openpty()
300 debug(f"Got master_fd '{master_fd}', slave_fd '{slave_fd}'")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000301
Petr Viktorin65cf1ad2021-01-19 14:03:12 +0100302 self.addCleanup(os.close, master_fd)
303
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600304 debug("Closing slave_fd")
305 os.close(slave_fd)
306
307 debug("Reading from master_fd")
Soumendra Ganguly74311ae2020-11-28 15:04:20 -0600308 try:
309 data = os.read(master_fd, 1)
310 except OSError: # Linux
311 data = b""
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600312
Soumendra Ganguly74311ae2020-11-28 15:04:20 -0600313 self.assertEqual(data, b"")
Gregory P. Smith05f59532012-02-16 00:29:12 -0800314
Miss Islington (bot)5d444432021-08-12 05:36:04 -0700315 def test_spawn_doesnt_hang(self):
316 pty.spawn([sys.executable, '-c', 'print("hi there")'])
317
Gregory P. Smith05f59532012-02-16 00:29:12 -0800318class SmallPtyTests(unittest.TestCase):
319 """These tests don't spawn children or hang."""
320
321 def setUp(self):
322 self.orig_stdin_fileno = pty.STDIN_FILENO
323 self.orig_stdout_fileno = pty.STDOUT_FILENO
Miss Islington (bot)5d444432021-08-12 05:36:04 -0700324 self.orig_pty_close = pty.close
325 self.orig_pty__copy = pty._copy
326 self.orig_pty_fork = pty.fork
Gregory P. Smith05f59532012-02-16 00:29:12 -0800327 self.orig_pty_select = pty.select
Miss Islington (bot)5d444432021-08-12 05:36:04 -0700328 self.orig_pty_setraw = pty.setraw
329 self.orig_pty_tcgetattr = pty.tcgetattr
330 self.orig_pty_tcsetattr = pty.tcsetattr
331 self.orig_pty_waitpid = pty.waitpid
Gregory P. Smith05f59532012-02-16 00:29:12 -0800332 self.fds = [] # A list of file descriptors to close.
Victor Stinnerb1f7f632012-03-06 02:04:58 +0100333 self.files = []
Gregory P. Smith05f59532012-02-16 00:29:12 -0800334 self.select_rfds_lengths = []
335 self.select_rfds_results = []
Miss Islington (bot)5d444432021-08-12 05:36:04 -0700336 self.tcsetattr_mode_setting = None
Gregory P. Smith05f59532012-02-16 00:29:12 -0800337
338 def tearDown(self):
339 pty.STDIN_FILENO = self.orig_stdin_fileno
340 pty.STDOUT_FILENO = self.orig_stdout_fileno
Miss Islington (bot)5d444432021-08-12 05:36:04 -0700341 pty.close = self.orig_pty_close
342 pty._copy = self.orig_pty__copy
343 pty.fork = self.orig_pty_fork
Gregory P. Smith05f59532012-02-16 00:29:12 -0800344 pty.select = self.orig_pty_select
Miss Islington (bot)5d444432021-08-12 05:36:04 -0700345 pty.setraw = self.orig_pty_setraw
346 pty.tcgetattr = self.orig_pty_tcgetattr
347 pty.tcsetattr = self.orig_pty_tcsetattr
348 pty.waitpid = self.orig_pty_waitpid
Victor Stinnerb1f7f632012-03-06 02:04:58 +0100349 for file in self.files:
350 try:
351 file.close()
352 except OSError:
353 pass
Gregory P. Smith05f59532012-02-16 00:29:12 -0800354 for fd in self.fds:
355 try:
356 os.close(fd)
Victor Stinnerb1f7f632012-03-06 02:04:58 +0100357 except OSError:
Gregory P. Smith05f59532012-02-16 00:29:12 -0800358 pass
359
360 def _pipe(self):
361 pipe_fds = os.pipe()
362 self.fds.extend(pipe_fds)
363 return pipe_fds
364
Victor Stinnerb1f7f632012-03-06 02:04:58 +0100365 def _socketpair(self):
366 socketpair = socket.socketpair()
367 self.files.extend(socketpair)
368 return socketpair
369
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600370 def _mock_select(self, rfds, wfds, xfds, timeout=0):
Gregory P. Smith05f59532012-02-16 00:29:12 -0800371 # This will raise IndexError when no more expected calls exist.
Soumendra Gangulyc13d8992020-11-25 07:41:25 -0600372 # This ignores the timeout
Gregory P. Smith05f59532012-02-16 00:29:12 -0800373 self.assertEqual(self.select_rfds_lengths.pop(0), len(rfds))
374 return self.select_rfds_results.pop(0), [], []
375
Miss Islington (bot)5d444432021-08-12 05:36:04 -0700376 def _make_mock_fork(self, pid):
377 def mock_fork():
378 return (pid, 12)
379 return mock_fork
380
381 def _mock_tcsetattr(self, fileno, opt, mode):
382 self.tcsetattr_mode_setting = mode
383
Gregory P. Smith05f59532012-02-16 00:29:12 -0800384 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
Gregory P. Smith05f59532012-02-16 00:29:12 -0800424 pty.select = self._mock_select
425 self.select_rfds_lengths.append(2)
426 self.select_rfds_results.append([mock_stdin_fd, masters[0]])
427 # We expect that both fds were removed from the fds list as they
428 # both encountered an EOF before the second select call.
429 self.select_rfds_lengths.append(0)
430
Miss Islington (bot)5d444432021-08-12 05:36:04 -0700431 # We expect the function to return without error.
432 self.assertEqual(pty._copy(masters[0]), None)
433
434 def test__restore_tty_mode_normal_return(self):
435 """Test that spawn resets the tty mode no when _copy returns normally."""
436
437 # PID 1 is returned from mocked fork to run the parent branch
438 # of code
439 pty.fork = self._make_mock_fork(1)
440
441 status_sentinel = object()
442 pty.waitpid = lambda _1, _2: [None, status_sentinel]
443 pty.close = lambda _: None
444
445 pty._copy = lambda _1, _2, _3: None
446
447 mode_sentinel = object()
448 pty.tcgetattr = lambda fd: mode_sentinel
449 pty.tcsetattr = self._mock_tcsetattr
450 pty.setraw = lambda _: None
451
452 self.assertEqual(pty.spawn([]), status_sentinel, "pty.waitpid process status not returned by pty.spawn")
453 self.assertEqual(self.tcsetattr_mode_setting, mode_sentinel, "pty.tcsetattr not called with original mode value")
Gregory P. Smith05f59532012-02-16 00:29:12 -0800454
455
Zachary Ware38c707e2015-04-13 15:00:43 -0500456def tearDownModule():
457 reap_children()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000458
Miss Islington (bot)5d444432021-08-12 05:36:04 -0700459
Guido van Rossumd8faa362007-04-27 19:54:29 +0000460if __name__ == "__main__":
Zachary Ware38c707e2015-04-13 15:00:43 -0500461 unittest.main()