blob: f623aa09620ec0c0cb48bcca687466e4797a5331 [file] [log] [blame]
R. David Murray95fb46c2009-04-21 13:06:04 +00001from test.test_support import verbose, run_unittest, import_module
2
3#Skip these tests if either fcntl or termios is not available
4fcntl = import_module('fcntl')
5import_module('termios')
6
Neal Norwitz1b59d102007-04-27 06:45:32 +00007import errno
Georg Brandl9decc0d2007-03-07 11:37:42 +00008import pty
9import os
Barry Warsaw25a38642007-04-13 18:47:14 +000010import sys
Gregory P. Smithb4b60562012-02-16 00:40:03 -080011import select
Georg Brandl9decc0d2007-03-07 11:37:42 +000012import signal
Gregory P. Smithb4b60562012-02-16 00:40:03 -080013import socket
Victor Stinner20cbc1d2017-10-02 02:58:09 -070014import io # readline
Georg Brandl9decc0d2007-03-07 11:37:42 +000015import unittest
Fred Drake4c136ee2000-06-30 23:22:35 +000016
Thomas Woutersb0dbeef2001-03-22 14:50:24 +000017TEST_STRING_1 = "I wish to buy a fish license.\n"
18TEST_STRING_2 = "For my pet fish, Eric.\n"
Fred Drake4c136ee2000-06-30 23:22:35 +000019
20if verbose:
21 def debug(msg):
22 print msg
23else:
24 def debug(msg):
25 pass
26
Georg Brandl9decc0d2007-03-07 11:37:42 +000027
Victor Stinner20cbc1d2017-10-02 02:58:09 -070028# Note that os.read() is nondeterministic so we need to be very careful
29# to make the test suite deterministic. A normal call to os.read() may
30# give us less than expected.
31#
32# Beware, on my Linux system, if I put 'foo\n' into a terminal fd, I get
33# back 'foo\r\n' at the other end. The behavior depends on the termios
34# setting. The newline translation may be OS-specific. To make the
35# test suite deterministic and OS-independent, the functions _readline
36# and normalize_output can be used.
37
Neal Norwitz84c95b92006-04-03 05:28:31 +000038def normalize_output(data):
39 # Some operating systems do conversions on newline. We could possibly
40 # fix that by doing the appropriate termios.tcsetattr()s. I couldn't
41 # figure out the right combo on Tru64 and I don't have an IRIX box.
Anthony Baxtera2a26b92006-04-05 17:30:38 +000042 # So just normalize the output and doc the problem O/Ses by allowing
Neal Norwitz84c95b92006-04-03 05:28:31 +000043 # certain combinations for some platforms, but avoid allowing other
44 # differences (like extra whitespace, trailing garbage, etc.)
45
46 # This is about the best we can do without getting some feedback
47 # from someone more knowledgable.
48
49 # OSF/1 (Tru64) apparently turns \n into \r\r\n.
50 if data.endswith('\r\r\n'):
Neal Norwitz9cc3b1c2006-04-26 06:26:12 +000051 return data.replace('\r\r\n', '\n')
Neal Norwitz84c95b92006-04-03 05:28:31 +000052
53 # IRIX apparently turns \n into \r\n.
54 if data.endswith('\r\n'):
Neal Norwitz9cc3b1c2006-04-26 06:26:12 +000055 return data.replace('\r\n', '\n')
Neal Norwitz84c95b92006-04-03 05:28:31 +000056
57 return data
58
Victor Stinner20cbc1d2017-10-02 02:58:09 -070059def _readline(fd):
60 """Read one line. May block forever if no newline is read."""
61 reader = io.FileIO(fd, mode='rb', closefd=False)
62 return reader.readline()
63
64
Georg Brandl9decc0d2007-03-07 11:37:42 +000065
Fred Drake4c136ee2000-06-30 23:22:35 +000066# Marginal testing of pty suite. Cannot do extensive 'do or fail' testing
67# because pty code is not too portable.
Neal Norwitz1b59d102007-04-27 06:45:32 +000068# XXX(nnorwitz): these tests leak fds when there is an error.
Georg Brandl9decc0d2007-03-07 11:37:42 +000069class PtyTest(unittest.TestCase):
70 def setUp(self):
Tim Petersea5962f2007-03-12 18:07:52 +000071 # isatty() and close() can hang on some platforms. Set an alarm
Georg Brandl9decc0d2007-03-07 11:37:42 +000072 # before running the test to make sure we don't hang forever.
73 self.old_alarm = signal.signal(signal.SIGALRM, self.handle_sig)
74 signal.alarm(10)
Tim Petersea5962f2007-03-12 18:07:52 +000075
Georg Brandl9decc0d2007-03-07 11:37:42 +000076 def tearDown(self):
77 # remove alarm, restore old alarm handler
78 signal.alarm(0)
79 signal.signal(signal.SIGALRM, self.old_alarm)
Tim Petersea5962f2007-03-12 18:07:52 +000080
Georg Brandl9decc0d2007-03-07 11:37:42 +000081 def handle_sig(self, sig, frame):
82 self.fail("isatty hung")
Tim Petersea5962f2007-03-12 18:07:52 +000083
Georg Brandl9decc0d2007-03-07 11:37:42 +000084 def test_basic(self):
85 try:
86 debug("Calling master_open()")
87 master_fd, slave_name = pty.master_open()
88 debug("Got master_fd '%d', slave_name '%s'" %
89 (master_fd, slave_name))
90 debug("Calling slave_open(%r)" % (slave_name,))
91 slave_fd = pty.slave_open(slave_name)
92 debug("Got slave_fd '%d'" % slave_fd)
93 except OSError:
94 # " An optional feature could not be imported " ... ?
Benjamin Petersonbec087f2009-03-26 21:10:30 +000095 raise unittest.SkipTest, "Pseudo-terminals (seemingly) not functional."
Fred Drake4c136ee2000-06-30 23:22:35 +000096
Georg Brandl9decc0d2007-03-07 11:37:42 +000097 self.assertTrue(os.isatty(slave_fd), 'slave_fd is not a tty')
Tim Petersea5962f2007-03-12 18:07:52 +000098
Neal Norwitz1b59d102007-04-27 06:45:32 +000099 # Solaris requires reading the fd before anything is returned.
100 # My guess is that since we open and close the slave fd
101 # in master_open(), we need to read the EOF.
102
103 # Ensure the fd is non-blocking in case there's nothing to read.
104 orig_flags = fcntl.fcntl(master_fd, fcntl.F_GETFL)
105 fcntl.fcntl(master_fd, fcntl.F_SETFL, orig_flags | os.O_NONBLOCK)
106 try:
107 s1 = os.read(master_fd, 1024)
Ezio Melotti2623a372010-11-21 13:34:58 +0000108 self.assertEqual('', s1)
Neal Norwitz1b59d102007-04-27 06:45:32 +0000109 except OSError, e:
110 if e.errno != errno.EAGAIN:
111 raise
112 # Restore the original flags.
113 fcntl.fcntl(master_fd, fcntl.F_SETFL, orig_flags)
114
Georg Brandl9decc0d2007-03-07 11:37:42 +0000115 debug("Writing to slave_fd")
116 os.write(slave_fd, TEST_STRING_1)
Victor Stinner20cbc1d2017-10-02 02:58:09 -0700117 s1 = _readline(master_fd)
Ezio Melotti2623a372010-11-21 13:34:58 +0000118 self.assertEqual('I wish to buy a fish license.\n',
119 normalize_output(s1))
Tim Petersea5962f2007-03-12 18:07:52 +0000120
Georg Brandl9decc0d2007-03-07 11:37:42 +0000121 debug("Writing chunked output")
122 os.write(slave_fd, TEST_STRING_2[:5])
123 os.write(slave_fd, TEST_STRING_2[5:])
Victor Stinner20cbc1d2017-10-02 02:58:09 -0700124 s2 = _readline(master_fd)
Ezio Melotti2623a372010-11-21 13:34:58 +0000125 self.assertEqual('For my pet fish, Eric.\n', normalize_output(s2))
Tim Petersea5962f2007-03-12 18:07:52 +0000126
Georg Brandl9decc0d2007-03-07 11:37:42 +0000127 os.close(slave_fd)
128 os.close(master_fd)
Tim Petersf733abb2007-01-30 03:03:46 +0000129
130
Georg Brandl9decc0d2007-03-07 11:37:42 +0000131 def test_fork(self):
132 debug("calling pty.fork()")
133 pid, master_fd = pty.fork()
134 if pid == pty.CHILD:
135 # stdout should be connected to a tty.
136 if not os.isatty(1):
137 debug("Child's fd 1 is not a tty?!")
138 os._exit(3)
Tim Petersea5962f2007-03-12 18:07:52 +0000139
Georg Brandl9decc0d2007-03-07 11:37:42 +0000140 # After pty.fork(), the child should already be a session leader.
141 # (on those systems that have that concept.)
142 debug("In child, calling os.setsid()")
143 try:
144 os.setsid()
145 except OSError:
146 # Good, we already were session leader
147 debug("Good: OSError was raised.")
148 pass
149 except AttributeError:
150 # Have pty, but not setsid()?
151 debug("No setsid() available?")
152 pass
153 except:
154 # We don't want this error to propagate, escaping the call to
155 # os._exit() and causing very peculiar behavior in the calling
156 # regrtest.py !
157 # Note: could add traceback printing here.
158 debug("An unexpected error was raised.")
159 os._exit(1)
160 else:
161 debug("os.setsid() succeeded! (bad!)")
162 os._exit(2)
163 os._exit(4)
164 else:
165 debug("Waiting for child (%d) to finish." % pid)
Barry Warsaw25a38642007-04-13 18:47:14 +0000166 # In verbose mode, we have to consume the debug output from the
167 # child or the child will block, causing this test to hang in the
168 # parent's waitpid() call. The child blocks after a
169 # platform-dependent amount of data is written to its fd. On
170 # Linux 2.6, it's 4000 bytes and the child won't block, but on OS
171 # X even the small writes in the child above will block it. Also
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200172 # on Linux, the read() will raise an OSError (input/output error)
Barry Warsaw25a38642007-04-13 18:47:14 +0000173 # when it tries to read past the end of the buffer but the child's
174 # already exited, so catch and discard those exceptions. It's not
175 # worth checking for EIO.
176 while True:
177 try:
178 data = os.read(master_fd, 80)
179 except OSError:
180 break
181 if not data:
182 break
183 sys.stdout.write(data.replace('\r\n', '\n'))
184
Georg Brandl9decc0d2007-03-07 11:37:42 +0000185 ##line = os.read(master_fd, 80)
186 ##lines = line.replace('\r\n', '\n').split('\n')
187 ##if False and lines != ['In child, calling os.setsid()',
188 ## 'Good: OSError was raised.', '']:
189 ## raise TestFailed("Unexpected output from child: %r" % line)
Tim Petersea5962f2007-03-12 18:07:52 +0000190
Georg Brandl9decc0d2007-03-07 11:37:42 +0000191 (pid, status) = os.waitpid(pid, 0)
192 res = status >> 8
193 debug("Child (%d) exited with status %d (%d)." % (pid, res, status))
194 if res == 1:
195 self.fail("Child raised an unexpected exception in os.setsid()")
196 elif res == 2:
197 self.fail("pty.fork() failed to make child a session leader.")
198 elif res == 3:
199 self.fail("Child spawned by pty.fork() did not have a tty as stdout")
200 elif res != 4:
201 self.fail("pty.fork() failed for unknown reasons.")
Tim Petersea5962f2007-03-12 18:07:52 +0000202
Georg Brandl9decc0d2007-03-07 11:37:42 +0000203 ##debug("Reading from master_fd now that the child has exited")
204 ##try:
205 ## s1 = os.read(master_fd, 1024)
206 ##except os.error:
207 ## pass
208 ##else:
209 ## raise TestFailed("Read from master_fd did not raise exception")
Tim Petersea5962f2007-03-12 18:07:52 +0000210
Georg Brandl9decc0d2007-03-07 11:37:42 +0000211 os.close(master_fd)
Tim Petersea5962f2007-03-12 18:07:52 +0000212
Georg Brandl9decc0d2007-03-07 11:37:42 +0000213 # pty.fork() passed.
Fred Drake4c136ee2000-06-30 23:22:35 +0000214
Gregory P. Smithb4b60562012-02-16 00:40:03 -0800215
216class SmallPtyTests(unittest.TestCase):
217 """These tests don't spawn children or hang."""
218
219 def setUp(self):
220 self.orig_stdin_fileno = pty.STDIN_FILENO
221 self.orig_stdout_fileno = pty.STDOUT_FILENO
222 self.orig_pty_select = pty.select
223 self.fds = [] # A list of file descriptors to close.
224 self.select_rfds_lengths = []
225 self.select_rfds_results = []
226
227 def tearDown(self):
228 pty.STDIN_FILENO = self.orig_stdin_fileno
229 pty.STDOUT_FILENO = self.orig_stdout_fileno
230 pty.select = self.orig_pty_select
231 for fd in self.fds:
232 try:
233 os.close(fd)
234 except:
235 pass
236
237 def _pipe(self):
238 pipe_fds = os.pipe()
239 self.fds.extend(pipe_fds)
240 return pipe_fds
241
242 def _mock_select(self, rfds, wfds, xfds):
243 # This will raise IndexError when no more expected calls exist.
244 self.assertEqual(self.select_rfds_lengths.pop(0), len(rfds))
245 return self.select_rfds_results.pop(0), [], []
246
247 def test__copy_to_each(self):
248 """Test the normal data case on both master_fd and stdin."""
249 read_from_stdout_fd, mock_stdout_fd = self._pipe()
250 pty.STDOUT_FILENO = mock_stdout_fd
251 mock_stdin_fd, write_to_stdin_fd = self._pipe()
252 pty.STDIN_FILENO = mock_stdin_fd
253 socketpair = socket.socketpair()
254 masters = [s.fileno() for s in socketpair]
255 self.fds.extend(masters)
256
257 # Feed data. Smaller than PIPEBUF. These writes will not block.
258 os.write(masters[1], b'from master')
259 os.write(write_to_stdin_fd, b'from stdin')
260
261 # Expect two select calls, the last one will cause IndexError
262 pty.select = self._mock_select
263 self.select_rfds_lengths.append(2)
264 self.select_rfds_results.append([mock_stdin_fd, masters[0]])
265 self.select_rfds_lengths.append(2)
266
267 with self.assertRaises(IndexError):
268 pty._copy(masters[0])
269
270 # Test that the right data went to the right places.
271 rfds = select.select([read_from_stdout_fd, masters[1]], [], [], 0)[0]
272 self.assertEqual([read_from_stdout_fd, masters[1]], rfds)
273 self.assertEqual(os.read(read_from_stdout_fd, 20), b'from master')
274 self.assertEqual(os.read(masters[1], 20), b'from stdin')
275
276 def test__copy_eof_on_all(self):
277 """Test the empty read EOF case on both master_fd and stdin."""
278 read_from_stdout_fd, mock_stdout_fd = self._pipe()
279 pty.STDOUT_FILENO = mock_stdout_fd
280 mock_stdin_fd, write_to_stdin_fd = self._pipe()
281 pty.STDIN_FILENO = mock_stdin_fd
282 socketpair = socket.socketpair()
283 masters = [s.fileno() for s in socketpair]
284 self.fds.extend(masters)
285
286 os.close(masters[1])
287 socketpair[1].close()
288 os.close(write_to_stdin_fd)
289
290 # Expect two select calls, the last one will cause IndexError
291 pty.select = self._mock_select
292 self.select_rfds_lengths.append(2)
293 self.select_rfds_results.append([mock_stdin_fd, masters[0]])
294 # We expect that both fds were removed from the fds list as they
295 # both encountered an EOF before the second select call.
296 self.select_rfds_lengths.append(0)
297
298 with self.assertRaises(IndexError):
299 pty._copy(masters[0])
300
301
Georg Brandl9decc0d2007-03-07 11:37:42 +0000302def test_main(verbose=None):
Gregory P. Smithb4b60562012-02-16 00:40:03 -0800303 run_unittest(SmallPtyTests, PtyTest)
Georg Brandl9decc0d2007-03-07 11:37:42 +0000304
305if __name__ == "__main__":
306 test_main()