blob: 92039e44ed1fbc4ca53021e33ccbb5d89d69b54c [file] [log] [blame]
R. David Murrayeb3615d2009-04-22 02:24:39 +00001from 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
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
11import signal
Guido van Rossumd8faa362007-04-27 19:54:29 +000012import unittest
Fred Drake4c136ee2000-06-30 23:22:35 +000013
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +000014TEST_STRING_1 = b"I wish to buy a fish license.\n"
15TEST_STRING_2 = b"For my pet fish, Eric.\n"
Fred Drake4c136ee2000-06-30 23:22:35 +000016
17if verbose:
18 def debug(msg):
Guido van Rossumbe19ed72007-02-09 05:37:30 +000019 print(msg)
Fred Drake4c136ee2000-06-30 23:22:35 +000020else:
21 def debug(msg):
22 pass
23
Guido van Rossumd8faa362007-04-27 19:54:29 +000024
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000025def normalize_output(data):
26 # Some operating systems do conversions on newline. We could possibly
27 # fix that by doing the appropriate termios.tcsetattr()s. I couldn't
28 # figure out the right combo on Tru64 and I don't have an IRIX box.
29 # So just normalize the output and doc the problem O/Ses by allowing
30 # certain combinations for some platforms, but avoid allowing other
31 # differences (like extra whitespace, trailing garbage, etc.)
32
33 # This is about the best we can do without getting some feedback
34 # from someone more knowledgable.
35
36 # OSF/1 (Tru64) apparently turns \n into \r\r\n.
Walter Dörwald812d8342007-05-29 18:57:42 +000037 if data.endswith(b'\r\r\n'):
38 return data.replace(b'\r\r\n', b'\n')
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000039
40 # IRIX apparently turns \n into \r\n.
Walter Dörwald812d8342007-05-29 18:57:42 +000041 if data.endswith(b'\r\n'):
42 return data.replace(b'\r\n', b'\n')
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000043
44 return data
45
Guido van Rossumd8faa362007-04-27 19:54:29 +000046
Fred Drake4c136ee2000-06-30 23:22:35 +000047# Marginal testing of pty suite. Cannot do extensive 'do or fail' testing
48# because pty code is not too portable.
Guido van Rossum360e4b82007-05-14 22:51:27 +000049# XXX(nnorwitz): these tests leak fds when there is an error.
Guido van Rossumd8faa362007-04-27 19:54:29 +000050class PtyTest(unittest.TestCase):
51 def setUp(self):
52 # isatty() and close() can hang on some platforms. Set an alarm
53 # before running the test to make sure we don't hang forever.
54 self.old_alarm = signal.signal(signal.SIGALRM, self.handle_sig)
55 signal.alarm(10)
Fred Drake4c136ee2000-06-30 23:22:35 +000056
Guido van Rossumd8faa362007-04-27 19:54:29 +000057 def tearDown(self):
58 # remove alarm, restore old alarm handler
59 signal.alarm(0)
60 signal.signal(signal.SIGALRM, self.old_alarm)
Neal Norwitz7d814522003-03-21 01:39:14 +000061
Guido van Rossumd8faa362007-04-27 19:54:29 +000062 def handle_sig(self, sig, frame):
63 self.fail("isatty hung")
Neal Norwitz7d814522003-03-21 01:39:14 +000064
Guido van Rossumd8faa362007-04-27 19:54:29 +000065 def test_basic(self):
66 try:
67 debug("Calling master_open()")
68 master_fd, slave_name = pty.master_open()
69 debug("Got master_fd '%d', slave_name '%s'" %
70 (master_fd, slave_name))
71 debug("Calling slave_open(%r)" % (slave_name,))
72 slave_fd = pty.slave_open(slave_name)
73 debug("Got slave_fd '%d'" % slave_fd)
74 except OSError:
75 # " An optional feature could not be imported " ... ?
Benjamin Petersone549ead2009-03-28 21:42:05 +000076 raise unittest.SkipTest("Pseudo-terminals (seemingly) not functional.")
Neal Norwitz7d814522003-03-21 01:39:14 +000077
Guido van Rossumd8faa362007-04-27 19:54:29 +000078 self.assertTrue(os.isatty(slave_fd), 'slave_fd is not a tty')
Neal Norwitz7d814522003-03-21 01:39:14 +000079
Guido van Rossum360e4b82007-05-14 22:51:27 +000080 # Solaris requires reading the fd before anything is returned.
81 # My guess is that since we open and close the slave fd
82 # in master_open(), we need to read the EOF.
83
84 # Ensure the fd is non-blocking in case there's nothing to read.
85 orig_flags = fcntl.fcntl(master_fd, fcntl.F_GETFL)
86 fcntl.fcntl(master_fd, fcntl.F_SETFL, orig_flags | os.O_NONBLOCK)
87 try:
88 s1 = os.read(master_fd, 1024)
Ezio Melottib3aedd42010-11-20 19:04:17 +000089 self.assertEqual(b'', s1)
Guido van Rossum360e4b82007-05-14 22:51:27 +000090 except OSError as e:
91 if e.errno != errno.EAGAIN:
92 raise
93 # Restore the original flags.
94 fcntl.fcntl(master_fd, fcntl.F_SETFL, orig_flags)
95
Guido van Rossumd8faa362007-04-27 19:54:29 +000096 debug("Writing to slave_fd")
97 os.write(slave_fd, TEST_STRING_1)
98 s1 = os.read(master_fd, 1024)
Ezio Melottib3aedd42010-11-20 19:04:17 +000099 self.assertEqual(b'I wish to buy a fish license.\n',
100 normalize_output(s1))
Neal Norwitz7d814522003-03-21 01:39:14 +0000101
Guido van Rossumd8faa362007-04-27 19:54:29 +0000102 debug("Writing chunked output")
103 os.write(slave_fd, TEST_STRING_2[:5])
104 os.write(slave_fd, TEST_STRING_2[5:])
105 s2 = os.read(master_fd, 1024)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000106 self.assertEqual(b'For my pet fish, Eric.\n', normalize_output(s2))
Neal Norwitz7d814522003-03-21 01:39:14 +0000107
Guido van Rossumd8faa362007-04-27 19:54:29 +0000108 os.close(slave_fd)
109 os.close(master_fd)
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000110
111
Guido van Rossumd8faa362007-04-27 19:54:29 +0000112 def test_fork(self):
113 debug("calling pty.fork()")
114 pid, master_fd = pty.fork()
115 if pid == pty.CHILD:
116 # stdout should be connected to a tty.
117 if not os.isatty(1):
118 debug("Child's fd 1 is not a tty?!")
119 os._exit(3)
Fred Drake4c136ee2000-06-30 23:22:35 +0000120
Guido van Rossumd8faa362007-04-27 19:54:29 +0000121 # After pty.fork(), the child should already be a session leader.
122 # (on those systems that have that concept.)
123 debug("In child, calling os.setsid()")
124 try:
125 os.setsid()
126 except OSError:
127 # Good, we already were session leader
128 debug("Good: OSError was raised.")
129 pass
130 except AttributeError:
131 # Have pty, but not setsid()?
132 debug("No setsid() available?")
133 pass
134 except:
135 # We don't want this error to propagate, escaping the call to
136 # os._exit() and causing very peculiar behavior in the calling
137 # regrtest.py !
138 # Note: could add traceback printing here.
139 debug("An unexpected error was raised.")
140 os._exit(1)
141 else:
142 debug("os.setsid() succeeded! (bad!)")
143 os._exit(2)
144 os._exit(4)
145 else:
146 debug("Waiting for child (%d) to finish." % pid)
147 # In verbose mode, we have to consume the debug output from the
148 # child or the child will block, causing this test to hang in the
149 # parent's waitpid() call. The child blocks after a
150 # platform-dependent amount of data is written to its fd. On
151 # Linux 2.6, it's 4000 bytes and the child won't block, but on OS
152 # X even the small writes in the child above will block it. Also
153 # on Linux, the read() will throw an OSError (input/output error)
154 # when it tries to read past the end of the buffer but the child's
155 # already exited, so catch and discard those exceptions. It's not
156 # worth checking for EIO.
157 while True:
158 try:
159 data = os.read(master_fd, 80)
160 except OSError:
161 break
162 if not data:
163 break
Alexandre Vassalottia351f772008-03-03 02:59:49 +0000164 sys.stdout.write(str(data.replace(b'\r\n', b'\n'),
165 encoding='ascii'))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000166
167 ##line = os.read(master_fd, 80)
168 ##lines = line.replace('\r\n', '\n').split('\n')
169 ##if False and lines != ['In child, calling os.setsid()',
170 ## 'Good: OSError was raised.', '']:
171 ## raise TestFailed("Unexpected output from child: %r" % line)
172
173 (pid, status) = os.waitpid(pid, 0)
174 res = status >> 8
175 debug("Child (%d) exited with status %d (%d)." % (pid, res, status))
176 if res == 1:
177 self.fail("Child raised an unexpected exception in os.setsid()")
178 elif res == 2:
179 self.fail("pty.fork() failed to make child a session leader.")
180 elif res == 3:
181 self.fail("Child spawned by pty.fork() did not have a tty as stdout")
182 elif res != 4:
183 self.fail("pty.fork() failed for unknown reasons.")
184
185 ##debug("Reading from master_fd now that the child has exited")
186 ##try:
187 ## s1 = os.read(master_fd, 1024)
188 ##except os.error:
189 ## pass
190 ##else:
191 ## raise TestFailed("Read from master_fd did not raise exception")
192
193 os.close(master_fd)
194
195 # pty.fork() passed.
196
197def test_main(verbose=None):
198 run_unittest(PtyTest)
199
200if __name__ == "__main__":
201 test_main()