blob: 5ce387beb4ca983364440dbef9e7df66d86485a1 [file] [log] [blame]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001import pty
2import os
3import sys
4import 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):
Guido van Rossumbe19ed72007-02-09 05:37:30 +000013 print(msg)
Fred Drake4c136ee2000-06-30 23:22:35 +000014else:
15 def debug(msg):
16 pass
17
Guido van Rossumd8faa362007-04-27 19:54:29 +000018
Thomas Wouters49fd7fa2006-04-21 10:40:58 +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.
23 # So just normalize the output and doc the problem O/Ses by allowing
24 # 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'):
Thomas Wouters477c8d52006-05-27 19:21:47 +000032 return data.replace('\r\r\n', '\n')
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000033
34 # IRIX apparently turns \n into \r\n.
35 if data.endswith('\r\n'):
Thomas Wouters477c8d52006-05-27 19:21:47 +000036 return data.replace('\r\n', '\n')
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000037
38 return data
39
Guido van Rossumd8faa362007-04-27 19:54:29 +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.
Guido van Rossumd8faa362007-04-27 19:54:29 +000043class PtyTest(unittest.TestCase):
44 def setUp(self):
45 # isatty() and close() can hang on some platforms. Set an alarm
46 # 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)
Fred Drake4c136ee2000-06-30 23:22:35 +000049
Guido van Rossumd8faa362007-04-27 19:54:29 +000050 def tearDown(self):
51 # remove alarm, restore old alarm handler
52 signal.alarm(0)
53 signal.signal(signal.SIGALRM, self.old_alarm)
Neal Norwitz7d814522003-03-21 01:39:14 +000054
Guido van Rossumd8faa362007-04-27 19:54:29 +000055 def handle_sig(self, sig, frame):
56 self.fail("isatty hung")
Neal Norwitz7d814522003-03-21 01:39:14 +000057
Guido van Rossumd8faa362007-04-27 19:54:29 +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."
Neal Norwitz7d814522003-03-21 01:39:14 +000070
Guido van Rossumd8faa362007-04-27 19:54:29 +000071 self.assertTrue(os.isatty(slave_fd), 'slave_fd is not a tty')
Neal Norwitz7d814522003-03-21 01:39:14 +000072
Guido van Rossumd8faa362007-04-27 19:54:29 +000073 debug("Writing to slave_fd")
74 os.write(slave_fd, TEST_STRING_1)
75 s1 = os.read(master_fd, 1024)
76 self.assertEquals('I wish to buy a fish license.\n',
77 normalize_output(s1))
Neal Norwitz7d814522003-03-21 01:39:14 +000078
Guido van Rossumd8faa362007-04-27 19:54:29 +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))
Neal Norwitz7d814522003-03-21 01:39:14 +000084
Guido van Rossumd8faa362007-04-27 19:54:29 +000085 os.close(slave_fd)
86 os.close(master_fd)
Thomas Wouters9fe394c2007-02-05 01:24:16 +000087
88
Guido van Rossumd8faa362007-04-27 19:54:29 +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)
Fred Drake4c136ee2000-06-30 23:22:35 +000097
Guido van Rossumd8faa362007-04-27 19:54:29 +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)
124 # 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
143 ##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)
148
149 (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.")
160
161 ##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")
168
169 os.close(master_fd)
170
171 # pty.fork() passed.
172
173def test_main(verbose=None):
174 run_unittest(PtyTest)
175
176if __name__ == "__main__":
177 test_main()