blob: 11fff3483e7e60d91cead35005ecca33c880215a [file] [log] [blame]
Georg Brandl9decc0d2007-03-07 11:37:42 +00001import pty
2import os
Barry Warsaw25a38642007-04-13 18:47:14 +00003import sys
Georg Brandl9decc0d2007-03-07 11:37:42 +00004import signal
5from test.test_support import verbose, TestSkipped, run_unittest
6import unittest
Fred Drake4c136ee2000-06-30 23:22:35 +00007
Thomas Woutersb0dbeef2001-03-22 14:50:24 +00008TEST_STRING_1 = "I wish to buy a fish license.\n"
9TEST_STRING_2 = "For my pet fish, Eric.\n"
Fred Drake4c136ee2000-06-30 23:22:35 +000010
11if verbose:
12 def debug(msg):
13 print msg
14else:
15 def debug(msg):
16 pass
17
Georg Brandl9decc0d2007-03-07 11:37:42 +000018
Neal Norwitz84c95b92006-04-03 05:28:31 +000019def normalize_output(data):
20 # Some operating systems do conversions on newline. We could possibly
21 # fix that by doing the appropriate termios.tcsetattr()s. I couldn't
22 # figure out the right combo on Tru64 and I don't have an IRIX box.
Anthony Baxtera2a26b92006-04-05 17:30:38 +000023 # So just normalize the output and doc the problem O/Ses by allowing
Neal Norwitz84c95b92006-04-03 05:28:31 +000024 # certain combinations for some platforms, but avoid allowing other
25 # differences (like extra whitespace, trailing garbage, etc.)
26
27 # This is about the best we can do without getting some feedback
28 # from someone more knowledgable.
29
30 # OSF/1 (Tru64) apparently turns \n into \r\r\n.
31 if data.endswith('\r\r\n'):
Neal Norwitz9cc3b1c2006-04-26 06:26:12 +000032 return data.replace('\r\r\n', '\n')
Neal Norwitz84c95b92006-04-03 05:28:31 +000033
34 # IRIX apparently turns \n into \r\n.
35 if data.endswith('\r\n'):
Neal Norwitz9cc3b1c2006-04-26 06:26:12 +000036 return data.replace('\r\n', '\n')
Neal Norwitz84c95b92006-04-03 05:28:31 +000037
38 return data
39
Georg Brandl9decc0d2007-03-07 11:37:42 +000040
Fred Drake4c136ee2000-06-30 23:22:35 +000041# Marginal testing of pty suite. Cannot do extensive 'do or fail' testing
42# because pty code is not too portable.
Georg Brandl9decc0d2007-03-07 11:37:42 +000043class PtyTest(unittest.TestCase):
44 def setUp(self):
Tim Petersea5962f2007-03-12 18:07:52 +000045 # isatty() and close() can hang on some platforms. Set an alarm
Georg Brandl9decc0d2007-03-07 11:37:42 +000046 # before running the test to make sure we don't hang forever.
47 self.old_alarm = signal.signal(signal.SIGALRM, self.handle_sig)
48 signal.alarm(10)
Tim Petersea5962f2007-03-12 18:07:52 +000049
Georg Brandl9decc0d2007-03-07 11:37:42 +000050 def tearDown(self):
51 # remove alarm, restore old alarm handler
52 signal.alarm(0)
53 signal.signal(signal.SIGALRM, self.old_alarm)
Tim Petersea5962f2007-03-12 18:07:52 +000054
Georg Brandl9decc0d2007-03-07 11:37:42 +000055 def handle_sig(self, sig, frame):
56 self.fail("isatty hung")
Tim Petersea5962f2007-03-12 18:07:52 +000057
Georg Brandl9decc0d2007-03-07 11:37:42 +000058 def test_basic(self):
59 try:
60 debug("Calling master_open()")
61 master_fd, slave_name = pty.master_open()
62 debug("Got master_fd '%d', slave_name '%s'" %
63 (master_fd, slave_name))
64 debug("Calling slave_open(%r)" % (slave_name,))
65 slave_fd = pty.slave_open(slave_name)
66 debug("Got slave_fd '%d'" % slave_fd)
67 except OSError:
68 # " An optional feature could not be imported " ... ?
69 raise TestSkipped, "Pseudo-terminals (seemingly) not functional."
Fred Drake4c136ee2000-06-30 23:22:35 +000070
Georg Brandl9decc0d2007-03-07 11:37:42 +000071 self.assertTrue(os.isatty(slave_fd), 'slave_fd is not a tty')
Tim Petersea5962f2007-03-12 18:07:52 +000072
Georg Brandl9decc0d2007-03-07 11:37:42 +000073 debug("Writing to slave_fd")
74 os.write(slave_fd, TEST_STRING_1)
75 s1 = os.read(master_fd, 1024)
Tim Petersea5962f2007-03-12 18:07:52 +000076 self.assertEquals('I wish to buy a fish license.\n',
Georg Brandl9decc0d2007-03-07 11:37:42 +000077 normalize_output(s1))
Tim Petersea5962f2007-03-12 18:07:52 +000078
Georg Brandl9decc0d2007-03-07 11:37:42 +000079 debug("Writing chunked output")
80 os.write(slave_fd, TEST_STRING_2[:5])
81 os.write(slave_fd, TEST_STRING_2[5:])
82 s2 = os.read(master_fd, 1024)
83 self.assertEquals('For my pet fish, Eric.\n', normalize_output(s2))
Tim Petersea5962f2007-03-12 18:07:52 +000084
Georg Brandl9decc0d2007-03-07 11:37:42 +000085 os.close(slave_fd)
86 os.close(master_fd)
Tim Petersf733abb2007-01-30 03:03:46 +000087
88
Georg Brandl9decc0d2007-03-07 11:37:42 +000089 def test_fork(self):
90 debug("calling pty.fork()")
91 pid, master_fd = pty.fork()
92 if pid == pty.CHILD:
93 # stdout should be connected to a tty.
94 if not os.isatty(1):
95 debug("Child's fd 1 is not a tty?!")
96 os._exit(3)
Tim Petersea5962f2007-03-12 18:07:52 +000097
Georg Brandl9decc0d2007-03-07 11:37:42 +000098 # After pty.fork(), the child should already be a session leader.
99 # (on those systems that have that concept.)
100 debug("In child, calling os.setsid()")
101 try:
102 os.setsid()
103 except OSError:
104 # Good, we already were session leader
105 debug("Good: OSError was raised.")
106 pass
107 except AttributeError:
108 # Have pty, but not setsid()?
109 debug("No setsid() available?")
110 pass
111 except:
112 # We don't want this error to propagate, escaping the call to
113 # os._exit() and causing very peculiar behavior in the calling
114 # regrtest.py !
115 # Note: could add traceback printing here.
116 debug("An unexpected error was raised.")
117 os._exit(1)
118 else:
119 debug("os.setsid() succeeded! (bad!)")
120 os._exit(2)
121 os._exit(4)
122 else:
123 debug("Waiting for child (%d) to finish." % pid)
Barry Warsaw25a38642007-04-13 18:47:14 +0000124 # In verbose mode, we have to consume the debug output from the
125 # child or the child will block, causing this test to hang in the
126 # parent's waitpid() call. The child blocks after a
127 # platform-dependent amount of data is written to its fd. On
128 # Linux 2.6, it's 4000 bytes and the child won't block, but on OS
129 # X even the small writes in the child above will block it. Also
130 # on Linux, the read() will throw an OSError (input/output error)
131 # when it tries to read past the end of the buffer but the child's
132 # already exited, so catch and discard those exceptions. It's not
133 # worth checking for EIO.
134 while True:
135 try:
136 data = os.read(master_fd, 80)
137 except OSError:
138 break
139 if not data:
140 break
141 sys.stdout.write(data.replace('\r\n', '\n'))
142
Georg Brandl9decc0d2007-03-07 11:37:42 +0000143 ##line = os.read(master_fd, 80)
144 ##lines = line.replace('\r\n', '\n').split('\n')
145 ##if False and lines != ['In child, calling os.setsid()',
146 ## 'Good: OSError was raised.', '']:
147 ## raise TestFailed("Unexpected output from child: %r" % line)
Tim Petersea5962f2007-03-12 18:07:52 +0000148
Georg Brandl9decc0d2007-03-07 11:37:42 +0000149 (pid, status) = os.waitpid(pid, 0)
150 res = status >> 8
151 debug("Child (%d) exited with status %d (%d)." % (pid, res, status))
152 if res == 1:
153 self.fail("Child raised an unexpected exception in os.setsid()")
154 elif res == 2:
155 self.fail("pty.fork() failed to make child a session leader.")
156 elif res == 3:
157 self.fail("Child spawned by pty.fork() did not have a tty as stdout")
158 elif res != 4:
159 self.fail("pty.fork() failed for unknown reasons.")
Tim Petersea5962f2007-03-12 18:07:52 +0000160
Georg Brandl9decc0d2007-03-07 11:37:42 +0000161 ##debug("Reading from master_fd now that the child has exited")
162 ##try:
163 ## s1 = os.read(master_fd, 1024)
164 ##except os.error:
165 ## pass
166 ##else:
167 ## raise TestFailed("Read from master_fd did not raise exception")
Tim Petersea5962f2007-03-12 18:07:52 +0000168
Georg Brandl9decc0d2007-03-07 11:37:42 +0000169 os.close(master_fd)
Tim Petersea5962f2007-03-12 18:07:52 +0000170
Georg Brandl9decc0d2007-03-07 11:37:42 +0000171 # pty.fork() passed.
Fred Drake4c136ee2000-06-30 23:22:35 +0000172
Georg Brandl9decc0d2007-03-07 11:37:42 +0000173def test_main(verbose=None):
174 run_unittest(PtyTest)
175
176if __name__ == "__main__":
177 test_main()