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