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