Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(462)

Side by Side Diff: third_party/twisted_8_1/twisted/test/test_stdio.py

Issue 12261012: Remove third_party/twisted_8_1 (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/tools/build
Patch Set: Created 7 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
1 # Copyright (c) 2006-2007 Twisted Matrix Laboratories.
2 # See LICENSE for details.
3
4 import os, sys
5
6 from twisted.trial import unittest
7 from twisted.python import filepath
8 from twisted.internet import error, defer, protocol, reactor
9
10
11 # A short string which is intended to appear here and nowhere else,
12 # particularly not in any random garbage output CPython unavoidable
13 # generates (such as in warning text and so forth). This is searched
14 # for in the output from stdio_test_lastwrite.py and if it is found at
15 # the end, the functionality works.
16 UNIQUE_LAST_WRITE_STRING = 'xyz123abc Twisted is great!'
17
18
19 class StandardIOTestProcessProtocol(protocol.ProcessProtocol):
20 """
21 Test helper for collecting output from a child process and notifying
22 something when it exits.
23
24 @ivar onConnection: A L{defer.Deferred} which will be called back with
25 C{None} when the connection to the child process is established.
26
27 @ivar onCompletion: A L{defer.Deferred} which will be errbacked with the
28 failure associated with the child process exiting when it exits.
29
30 @ivar onDataReceived: A L{defer.Deferred} which will be called back with
31 this instance whenever C{childDataReceived} is called, or C{None} to
32 suppress these callbacks.
33
34 @ivar data: A C{dict} mapping file descriptors to strings containing all
35 bytes received from the child process on each file descriptor.
36 """
37 onDataReceived = None
38
39 def __init__(self):
40 self.onConnection = defer.Deferred()
41 self.onCompletion = defer.Deferred()
42 self.data = {}
43
44
45 def connectionMade(self):
46 self.onConnection.callback(None)
47
48
49 def childDataReceived(self, name, bytes):
50 """
51 Record all bytes received from the child process in the C{data}
52 dictionary. Fire C{onDataReceived} if it is not C{None}.
53 """
54 self.data[name] = self.data.get(name, '') + bytes
55 if self.onDataReceived is not None:
56 d, self.onDataReceived = self.onDataReceived, None
57 d.callback(self)
58
59
60 def processEnded(self, reason):
61 self.onCompletion.callback(reason)
62
63
64
65 class StandardInputOutputTestCase(unittest.TestCase):
66 def _spawnProcess(self, proto, sibling, *args, **kw):
67 """
68 Launch a child Python process and communicate with it using the
69 given ProcessProtocol.
70
71 @param proto: A L{ProcessProtocol} instance which will be connected
72 to the child process.
73
74 @param sibling: The basename of a file containing the Python program
75 to run in the child process.
76
77 @param *args: strings which will be passed to the child process on
78 the command line as C{argv[2:]}.
79
80 @param **kw: additional arguments to pass to L{reactor.spawnProcess}.
81
82 @return: The L{IProcessTransport} provider for the spawned process.
83 """
84 import twisted
85 subenv = dict(os.environ)
86 subenv['PYTHONPATH'] = os.pathsep.join(
87 [os.path.abspath(
88 os.path.dirname(os.path.dirname(twisted.__file__))),
89 subenv.get('PYTHONPATH', '')
90 ])
91 args = [sys.executable,
92 filepath.FilePath(__file__).sibling(sibling).path,
93 reactor.__class__.__module__] + list(args)
94 return reactor.spawnProcess(
95 proto,
96 sys.executable,
97 args,
98 env=subenv,
99 **kw)
100
101
102 def _requireFailure(self, d, callback):
103 def cb(result):
104 self.fail("Process terminated with non-Failure: %r" % (result,))
105 def eb(err):
106 return callback(err)
107 return d.addCallbacks(cb, eb)
108
109
110 def test_loseConnection(self):
111 """
112 Verify that a protocol connected to L{StandardIO} can disconnect
113 itself using C{transport.loseConnection}.
114 """
115 p = StandardIOTestProcessProtocol()
116 d = p.onCompletion
117 self._spawnProcess(p, 'stdio_test_loseconn.py')
118
119 def processEnded(reason):
120 self.failIfIn(1, p.data)
121 reason.trap(error.ProcessDone)
122 return self._requireFailure(d, processEnded)
123
124
125 def test_lastWriteReceived(self):
126 """
127 Verify that a write made directly to stdout using L{os.write}
128 after StandardIO has finished is reliably received by the
129 process reading that stdout.
130 """
131 p = StandardIOTestProcessProtocol()
132
133 # Note: the OS X bug which prompted the addition of this test
134 # is an apparent race condition involving non-blocking PTYs.
135 # Delaying the parent process significantly increases the
136 # likelihood of the race going the wrong way. If you need to
137 # fiddle with this code at all, uncommenting the next line
138 # will likely make your life much easier. It is commented out
139 # because it makes the test quite slow.
140
141 # p.onConnection.addCallback(lambda ign: __import__('time').sleep(5))
142
143 try:
144 self._spawnProcess(
145 p, 'stdio_test_lastwrite.py', UNIQUE_LAST_WRITE_STRING,
146 usePTY=True)
147 except ValueError, e:
148 # Some platforms don't work with usePTY=True
149 raise unittest.SkipTest(str(e))
150
151 def processEnded(reason):
152 """
153 Asserts that the parent received the bytes written by the child
154 immediately after the child starts.
155 """
156 self.assertTrue(
157 p.data[1].endswith(UNIQUE_LAST_WRITE_STRING),
158 "Received %r from child, did not find expected bytes." % (
159 p.data,))
160 reason.trap(error.ProcessDone)
161 return self._requireFailure(p.onCompletion, processEnded)
162
163
164 def test_hostAndPeer(self):
165 """
166 Verify that the transport of a protocol connected to L{StandardIO}
167 has C{getHost} and C{getPeer} methods.
168 """
169 p = StandardIOTestProcessProtocol()
170 d = p.onCompletion
171 self._spawnProcess(p, 'stdio_test_hostpeer.py')
172
173 def processEnded(reason):
174 host, peer = p.data[1].splitlines()
175 self.failUnless(host)
176 self.failUnless(peer)
177 reason.trap(error.ProcessDone)
178 return self._requireFailure(d, processEnded)
179
180
181 def test_write(self):
182 """
183 Verify that the C{write} method of the transport of a protocol
184 connected to L{StandardIO} sends bytes to standard out.
185 """
186 p = StandardIOTestProcessProtocol()
187 d = p.onCompletion
188
189 self._spawnProcess(p, 'stdio_test_write.py')
190
191 def processEnded(reason):
192 self.assertEquals(p.data[1], 'ok!')
193 reason.trap(error.ProcessDone)
194 return self._requireFailure(d, processEnded)
195
196
197 def test_writeSequence(self):
198 """
199 Verify that the C{writeSequence} method of the transport of a
200 protocol connected to L{StandardIO} sends bytes to standard out.
201 """
202 p = StandardIOTestProcessProtocol()
203 d = p.onCompletion
204
205 self._spawnProcess(p, 'stdio_test_writeseq.py')
206
207 def processEnded(reason):
208 self.assertEquals(p.data[1], 'ok!')
209 reason.trap(error.ProcessDone)
210 return self._requireFailure(d, processEnded)
211
212
213 def _junkPath(self):
214 junkPath = self.mktemp()
215 junkFile = file(junkPath, 'w')
216 for i in xrange(1024):
217 junkFile.write(str(i) + '\n')
218 junkFile.close()
219 return junkPath
220
221
222 def test_producer(self):
223 """
224 Verify that the transport of a protocol connected to L{StandardIO}
225 is a working L{IProducer} provider.
226 """
227 p = StandardIOTestProcessProtocol()
228 d = p.onCompletion
229
230 written = []
231 toWrite = range(100)
232
233 def connectionMade(ign):
234 if toWrite:
235 written.append(str(toWrite.pop()) + "\n")
236 proc.write(written[-1])
237 reactor.callLater(0.01, connectionMade, None)
238
239 proc = self._spawnProcess(p, 'stdio_test_producer.py')
240
241 p.onConnection.addCallback(connectionMade)
242
243 def processEnded(reason):
244 self.assertEquals(p.data[1], ''.join(written))
245 self.failIf(toWrite, "Connection lost with %d writes left to go." % (len(toWrite),))
246 reason.trap(error.ProcessDone)
247 return self._requireFailure(d, processEnded)
248
249
250 def test_consumer(self):
251 """
252 Verify that the transport of a protocol connected to L{StandardIO}
253 is a working L{IConsumer} provider.
254 """
255 p = StandardIOTestProcessProtocol()
256 d = p.onCompletion
257
258 junkPath = self._junkPath()
259
260 self._spawnProcess(p, 'stdio_test_consumer.py', junkPath)
261
262 def processEnded(reason):
263 self.assertEquals(p.data[1], file(junkPath).read())
264 reason.trap(error.ProcessDone)
265 return self._requireFailure(d, processEnded)
OLDNEW
« no previous file with comments | « third_party/twisted_8_1/twisted/test/test_stateful.py ('k') | third_party/twisted_8_1/twisted/test/test_strcred.py » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698