我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用twisted.python.failure.Failure()。
def _doReadOrWrite(self, selectable, fd, event, POLLIN, POLLOUT, log, faildict={ error.ConnectionDone: failure.Failure(error.ConnectionDone()), error.ConnectionLost: failure.Failure(error.ConnectionLost()) }): why = None inRead = False if event & POLL_DISCONNECTED and not (event & POLLIN): why = main.CONNECTION_LOST else: try: if event & POLLIN: why = selectable.doRead() inRead = True if not why and event & POLLOUT: why = selectable.doWrite() inRead = False if not selectable.fileno() == fd: why = error.ConnectionFdescWentAway('Filedescriptor went away') inRead = False except: log.deferr() why = sys.exc_info()[1] if why: self._disconnectSelectable(selectable, why, inRead)
def _response(self, _, driver, spider): body = driver.execute_script('return document.documentElement.innerHTML') if body.startswith( "<head></head>"): # selenium ????http??????,???????????????,????body??????<head></head>???,?????? body = driver.execute_script('return document.documentElement.textContent') url = driver.current_url respcls = responsetypes.from_args(url=url, body=body[:100].encode('utf-8')) response = respcls(url=url, body=body, encoding='utf-8') response_failed = getattr(spider, 'response_failed', None) if response_failed and callable(response_failed) and response_failed(response, driver): driver.quit() return defer.fail(Failure()) else: self.queue.put(driver) # ?driver????queue return defer.succeed(response) # ??response??
def test_authenticate(self): d = defer.Deferred() def auth(u, p): try: self.assertEqual(u, 'u') self.assertEqual(p, 'p') except: d.errback(failure.Failure()) else: d.callback(None) gw = twisted.TwistedGateway({'echo': lambda x: x}, authenticator=auth) self.service_request = gateway.ServiceRequest( None, gw.services['echo'], None ) gw.authenticateRequest(self.service_request, 'u', 'p') return d
def test_exposed_authenticate(self): d = defer.Deferred() def auth(request, u, p): try: self.assertEqual(request, 'foo') self.assertEqual(u, 'u') self.assertEqual(p, 'p') except: d.errback(failure.Failure()) else: d.callback(None) auth = gateway.expose_request(auth) gw = twisted.TwistedGateway({'echo': lambda x: x}, authenticator=auth) self.service_request = gateway.ServiceRequest( None, gw.services['echo'], None ) gw.authenticateRequest( self.service_request, 'u', 'p', http_request='foo' ) return d
def handleEndHeaders(self): if self._finished: return self._finished = 1 # I think we need this because of HTTPClient if self.connected: self.transport.loseConnection() authHeader = 'authentication-info' _interHeader = 'www-authenticate' if self.headers.has_key(_interHeader): authHeader = _interHeader try: info = self.headers[authHeader] status = info['da-status'] handler = getattr(self, 'login_%s' % (status,), None) if handler: handler(info) else: raise Exception() except Exception, e: self.deferred.errback(failure.Failure(e))
def processOne(self, deferred): if self.stopping: deferred.callback(self.root) return try: self.remaining=self.iterator.next() except StopIteration: self.stopping=1 except: deferred.errback(failure.Failure()) if self.remaining%10==0: reactor.callLater(0, self.updateBar, deferred) if self.remaining%100==0: log.msg(self.remaining) reactor.callLater(0, self.processOne, deferred)
def _cbGetMultipleNext(self, res, files, local): if isinstance(res, failure.Failure): self._printFailure(res) elif res: self.transport.write(res) if not res.endswith('\n'): self.transport.write('\n') if not files: return f = files.pop(0)[0] lf = file(os.path.join(local, os.path.split(f)[1]), 'w', 0) path = os.path.join(self.currentDirectory, f) d = self.client.openFile(path, filetransfer.FXF_READ, {}) d.addCallback(self._cbGetOpenFile, lf) d.addErrback(self._ebCloseLf, lf) d.addBoth(self._cbGetMultipleNext, files, local) return d
def _cbPutMultipleNext(self, res, files, path): if isinstance(res, failure.Failure): self._printFailure(res) elif res: self.transport.write(res) if not res.endswith('\n'): self.transport.write('\n') f = None while files and not f: try: f = files.pop(0) lf = file(f, 'r') except: self._printFailure(failure.Failure()) f = None if not f: return name = os.path.split(f)[1] remote = os.path.join(self.currentDirectory, path, name) log.msg((name, remote, path)) d = self.client.openFile(remote, filetransfer.FXF_WRITE|filetransfer.FXF_CREAT, {}) d.addCallback(self._cbPutOpenFile, lf) d.addErrback(self._ebCloseLf, lf) d.addBoth(self._cbPutMultipleNext, files, path) return d
def packet_CLOSE(self, data): requestId = data[:4] data = data[4:] handle, data = getNS(data) assert data == '', 'still have data in CLOSE: %s' % repr(data) if handle in self.openFiles: fileObj = self.openFiles[handle] d = defer.maybeDeferred(fileObj.close) d.addCallback(self._cbClose, handle, requestId) d.addErrback(self._ebStatus, requestId, "close failed") elif handle in self.openDirs: dirObj = self.openDirs[handle][0] d = defer.maybeDeferred(dirObj.close) d.addCallback(self._cbClose, handle, requestId, 1) d.addErrback(self._ebStatus, requestId, "close failed") else: self._ebClose(failure.Failure(KeyError()), requestId)
def _cbRequestAvatarId(self, validKey, credentials): if not validKey: return failure.Failure(UnauthorizedLogin()) if not credentials.signature: return failure.Failure(error.ValidPublicKey()) else: try: pubKey = keys.getPublicKeyObject(data = credentials.blob) if keys.verifySignature(pubKey, credentials.signature, credentials.sigData): return credentials.username except: # any error should be treated as a failed login f = failure.Failure() log.err() return f return failure.Failure(UnauthorizedLogin())
def handleResponse(self, response): if self.quietLoss: return if self.failed: self.factory.noPage( failure.Failure( error.Error( self.status, self.message, response))) elif self.length != None and self.length != 0: self.factory.noPage(failure.Failure( PartialDownloadError(self.status, self.message, response))) else: self.factory.page(response) # server might be stupid and not close connection. admittedly # the fact we do only one request per connection is also # stupid... self.transport.loseConnection()
def process(self): "Process a request." # get site from channel self.site = self.channel.site # set various default headers self.setHeader('server', version) self.setHeader('date', http.datetimeToString()) self.setHeader('content-type', "text/html") # Resource Identification self.prepath = [] self.postpath = map(unquote, string.split(self.path[1:], '/')) try: resrc = self.site.getResourceFor(self) self.render(resrc) except: self.processingFailed(failure.Failure())
def loseConnection(self, _connDone=failure.Failure(main.CONNECTION_DONE)): """Close the connection at the next available opportunity. Call this to cause this FileDescriptor to lose its connection. It will first write any data that it has buffered. If there is data buffered yet to be written, this method will cause the transport to lose its connection as soon as it's done flushing its write buffer. If you have a producer registered, the connection won't be closed until the producer is finished. Therefore, make sure you unregister your producer when it's finished, or the connection will never close. """ if self.connected and not self.disconnecting: if self._writeDisconnected: # doWrite won't trigger the connection close anymore self.stopReading() self.stopWriting() self.connectionLost(_connDone) else: self.stopReading() self.startWriting() self.disconnecting = 1
def failIfNotConnected(self, err): """ Generic method called when the attemps to connect failed. It basically cleans everything it can: call connectionFailed, stop read and write, delete socket related members. """ if (self.connected or self.disconnected or not hasattr(self, "connector")): return self.connector.connectionFailed(failure.Failure(err)) if hasattr(self, "reactor"): # this doesn't happen if we failed in __init__ self.stopReading() self.stopWriting() del self.connector try: self._closeSocket() except AttributeError: pass else: del self.socket, self.fileno
def _doWriteOrRead(self, selectable, fd, filter): try: if filter == EVFILT_READ: why = selectable.doRead() if filter == EVFILT_WRITE: why = selectable.doWrite() if not selectable.fileno() == fd: why = main.CONNECTION_LOST except: why = sys.exc_info()[1] log.deferr() if why: self.removeReader(selectable) self.removeWriter(selectable) selectable.connectionLost(failure.Failure(why))
def maybeCallProcessEnded(self): # two things must happen before we call the ProcessProtocol's # processEnded method. 1: the child process must die and be reaped # (which calls our own processEnded method). 2: the child must close # their stdin/stdout/stderr fds, causing the pty to close, causing # our connectionLost method to be called. #2 can also be triggered # by calling .loseConnection(). if self.lostProcess == 2: try: exitCode = sig = None if self.status != -1: if os.WIFEXITED(self.status): exitCode = os.WEXITSTATUS(self.status) else: sig = os.WTERMSIG(self.status) else: pass # wonder when this happens if exitCode or sig: e = error.ProcessTerminated(exitCode, sig, self.status) else: e = error.ProcessDone(self.status) self.proto.processEnded(failure.Failure(e)) self.proto = None except: log.err()
def _runWrite(self, fd): closed = 0 try: closed = fd.doWrite() except: closed = sys.exc_info()[1] log.deferr() if closed: self.removeReader(fd) self.removeWriter(fd) try: fd.connectionLost(failure.Failure(closed)) except: log.deferr() elif closed is None: return 1
def errback(self, fail=None): """Run all error callbacks that have been added to this Deferred. Each callback will have its result passed as the first argument to the next; this way, the callbacks act as a 'processing chain'. Also, if the error-callback returns a non-Failure or doesn't raise an Exception, processing will continue on the *success*-callback chain. If the argument that's passed to me is not a failure.Failure instance, it will be embedded in one. If no argument is passed, a failure.Failure instance will be created based on the current traceback stack. Passing a string as `fail' is deprecated, and will be punished with a warning message. """ if not isinstance(fail, failure.Failure): fail = failure.Failure(fail) self._startRunCallbacks(fail)
def _cbDeferred(self, result, index, succeeded): """(internal) Callback for when one of my deferreds fires. """ self.resultList[index] = (succeeded, result) self.finishedCount += 1 if not self.called: if succeeded == SUCCESS and self.fireOnOneCallback: self.callback((result, index)) elif succeeded == FAILURE and self.fireOnOneErrback: self.errback(failure.Failure(FirstError(result, index))) elif self.finishedCount == len(self.resultList): self.callback(self.resultList) if succeeded == FAILURE and self.consumeErrors: result = None return result
def _disconnectSelectable(self, selectable, why, isRead, faildict={ error.ConnectionDone: failure.Failure(error.ConnectionDone()), error.ConnectionLost: failure.Failure(error.ConnectionLost()) }): """Utility function for disconnecting a selectable. Supports half-close notification, isRead should be boolean indicating whether error resulted from doRead(). """ self.removeReader(selectable) f = faildict.get(why.__class__) if f: if (isRead and why.__class__ == error.ConnectionDone and IHalfCloseableDescriptor.providedBy(selectable)): selectable.readConnectionLost(f) else: self.removeWriter(selectable) selectable.connectionLost(f) else: self.removeWriter(selectable) selectable.connectionLost(failure.Failure(why))
def testWakerOverflow(self): self.failure = None waiter = threading.Event() def threadedFunction(): # Hopefully a hundred thousand queued calls is enough to # trigger the error condition for i in xrange(100000): try: reactor.callFromThread(lambda: None) except: self.failure = failure.Failure() break waiter.set() reactor.callInThread(threadedFunction) waiter.wait(120) if not waiter.isSet(): self.fail("Timed out waiting for event") if self.failure is not None: return defer.fail(self.failure)
def failUnlessRaises(self, exception, f, *args, **kwargs): """fails the test unless calling the function C{f} with the given C{args} and C{kwargs} does not raise C{exception}. The failure will report the traceback and call stack of the unexpected exception. @param exception: exception type that is to be expected @param f: the function to call @return: The raised exception instance, if it is of the given type. @raise self.failureException: Raised if the function call does not raise an exception or if it raises an exception of a different type. """ try: result = f(*args, **kwargs) except exception, inst: return inst except: raise self.failureException('%s raised instead of %s:\n %s' % (sys.exc_info()[0], exception.__name__, failure.Failure().getTraceback())) else: raise self.failureException('%s not raised (%r returned)' % (exception.__name__, result))
def _cleanUp(self, result): try: if self.forceGarbageCollection: gc.collect() util._Janitor().postCaseCleanup() except util.FailureError, e: result.addError(self, e.original) self._passed = False except: result.cleanupErrors(failure.Failure()) self._passed = False for error in self._observer.getErrors(): result.addError(self, error) self._passed = False self.flushLoggedErrors() self._removeObserver() if self._passed: result.addSuccess(self)
def loadByNames(self, names, recurse=False): """ Construct a TestSuite containing all the tests found in 'names', where names is a list of fully qualified python names and/or filenames. The suite returned will have no duplicate tests, even if the same object is named twice. """ things = [] errors = [] for name in names: try: things.append(self.findByName(name)) except: errors.append(ErrorHolder(name, failure.Failure())) suites = [self.loadAnything(thing, recurse) for thing in sets.Set(things)] suites.extend(errors) return self.suiteFactory(suites)
def requestAvatarId(credentials): """ @param credentials: something which implements one of the interfaces in self.credentialInterfaces. @return: a Deferred which will fire a string which identifies an avatar, an empty tuple to specify an authenticated anonymous user (provided as checkers.ANONYMOUS) or fire a Failure(UnauthorizedLogin). Alternatively, return the result itself. """ # A note on anonymity - We do not want None as the value for anonymous # because it is too easy to accidentally return it. We do not want the # empty string, because it is too easy to mistype a password file. For # example, an .htpasswd file may contain the lines: ['hello:asdf', # 'world:asdf', 'goodbye', ':world']. This misconfiguration will have an # ill effect in any case, but accidentally granting anonymous access is a # worse failure mode than simply granting access to an untypeable # username. We do not want an instance of 'object', because that would # create potential problems with persistence.
def getStateToCopy(self): #state = self.__getstate__() state = self.__dict__.copy() state['tb'] = None state['frames'] = [] state['stack'] = [] if isinstance(self.value, failure.Failure): state['value'] = failure2Copyable(self.value, self.unsafeTracebacks) else: state['value'] = str(self.value) # Exception instance state['type'] = str(self.type) # Exception class if self.unsafeTracebacks: io = StringIO.StringIO() self.printTraceback(io) state['traceback'] = io.getvalue() else: state['traceback'] = 'Traceback unavailable\n' return state
def callRemote(self, name, *args, **kw): """Call a specially-designated local method. self.callRemote('x') will first try to invoke a method named sync_x and return its result (which should probably be a Deferred). Second, it will look for a method called async_x, which will be called and then have its result (or Failure) automatically wrapped in a Deferred. """ if hasattr(self, 'sync_'+name): return getattr(self, 'sync_'+name)(*args, **kw) try: method = getattr(self, "async_" + name) return defer.succeed(method(*args, **kw)) except: f = Failure() if self.reportAllTracebacks: f.printTraceback() return defer.fail(f)
def changeDirectory(self, path): """ Change the directory on the server and parse the result to determine if it was successful or not. @type path: C{str} @param path: The path to which to change. @return: a L{Deferred} which will be called back when the directory change has succeeded or and errbacked if an error occurrs. """ def cbParse(result): try: # The only valid code is 250 if int(result[0].split(' ', 1)[0]) == 250: return True else: raise ValueError except (IndexError, ValueError), e: return failure.Failure(CommandFailed(result)) return self.cwd(path).addCallback(cbParse)
def getDirectory(self): """ Returns the current remote directory. @return: a L{Deferred} that will be called back with a C{str} giving the remote directory or which will errback with L{CommandFailed} if an error response is returned. """ def cbParse(result): try: # The only valid code is 257 if int(result[0].split(' ', 1)[0]) != 257: raise ValueError except (IndexError, ValueError), e: return failure.Failure(CommandFailed(result)) path = parsePWDResponse(result[0]) if path is None: return failure.Failure(CommandFailed(result)) return path return self.pwd().addCallback(cbParse)
def loopback(server, client, logFile=None): """Run session between server and client. DEPRECATED in Twisted 2.5. Use loopbackAsync instead. """ import warnings warnings.warn('loopback() is deprecated (since Twisted 2.5). ' 'Use loopbackAsync() instead.', stacklevel=2, category=DeprecationWarning) from twisted.internet import reactor serverToClient = LoopbackRelay(client, logFile) clientToServer = LoopbackRelay(server, logFile) server.makeConnection(serverToClient) client.makeConnection(clientToServer) while 1: reactor.iterate(0.01) # this is to clear any deferreds serverToClient.clearBuffer() clientToServer.clearBuffer() if serverToClient.shouldLose: serverToClient.clearBuffer() server.connectionLost(failure.Failure(main.CONNECTION_DONE)) break elif clientToServer.shouldLose: client.connectionLost(failure.Failure(main.CONNECTION_DONE)) break reactor.iterate() # last gasp before I go away
def __init__(self, errorCode, description, fatal=False, local=None): """Create a remote error with an error code and description. @param errorCode: the AMP error code of this error. @param description: some text to show to the user. @param fatal: a boolean, true if this error should terminate the connection. @param local: a local Failure, if one exists. """ if local: localwhat = ' (local)' othertb = local.getBriefTraceback() else: localwhat = '' othertb = '' Exception.__init__(self, "Code<%s>%s: %s%s" % ( errorCode, localwhat, description, othertb)) self.local = local self.errorCode = errorCode self.description = description self.fatal = fatal
def dispatchCommand(self, box): """ A box with a _command key was received. Dispatch it to a local handler call it. @param proto: an AMP instance. @param box: an AmpBox to be dispatched. """ cmd = box[COMMAND] fObj = self.lookupFunction(cmd) if fObj is None: return fail(RemoteAmpError( UNHANDLED_ERROR_CODE, "Unhandled Command: %r" % (cmd,), False, local=Failure(UnhandledCommand()))) return maybeDeferred(fObj, box)
def _doCommand(self, proto): """ When we emit a ProtocolSwitchCommand, lock the protocol, but don't actually switch to the new protocol unless an acknowledgement is received. If an error is received, switch back. """ d = super(ProtocolSwitchCommand, self)._doCommand(proto) proto._lock() def switchNow(ign): innerProto = self.protoToSwitchToFactory.buildProtocol( proto.transport.getPeer()) proto._switchTo(innerProto, self.protoToSwitchToFactory) return ign def handle(ign): proto._locked = False self.protoToSwitchToFactory.clientConnectionFailed( None, Failure(CONNECTION_LOST)) return ign return d.addCallbacks(switchNow, handle)
def lookupZone(self, name, timeout = 10): if self.soa[0].lower() == name.lower(): # Wee hee hee hooo yea default_ttl = max(self.soa[1].minimum, self.soa[1].expire) if self.soa[1].ttl is not None: soa_ttl = self.soa[1].ttl else: soa_ttl = default_ttl results = [dns.RRHeader(self.soa[0], dns.SOA, dns.IN, soa_ttl, self.soa[1], auth=True)] for (k, r) in self.records.items(): for rec in r: if rec.ttl is not None: ttl = rec.ttl else: ttl = default_ttl if rec.TYPE != dns.SOA: results.append(dns.RRHeader(k, rec.TYPE, dns.IN, ttl, rec, auth=True)) results.append(results[0]) return defer.succeed((results, (), ())) return defer.fail(failure.Failure(dns.DomainError(name)))
def _lookup(self, name, cls, type, timeout): now = time.time() q = dns.Query(name, type, cls) try: when, (ans, auth, add) = self.cache[q] except KeyError: if self.verbose > 1: log.msg('Cache miss for ' + repr(name)) return defer.fail(failure.Failure(dns.DomainError(name))) else: if self.verbose: log.msg('Cache hit for ' + repr(name)) diff = now - when return defer.succeed(( [dns.RRHeader(str(r.name), r.type, r.cls, r.ttl - diff, r.payload) for r in ans], [dns.RRHeader(str(r.name), r.type, r.cls, r.ttl - diff, r.payload) for r in auth], [dns.RRHeader(str(r.name), r.type, r.cls, r.ttl - diff, r.payload) for r in add] ))
def console(self, message): """Pass a message to my clients' console. """ clients = self.clients.keys() origMessage = message compatMessage = None for client in clients: try: if not client.capabilities.has_key("Failure"): if compatMessage is None: compatMessage = origMessage[:] for i in xrange(len(message)): if ((message[i][0] == "exception") and isinstance(message[i][1], failure.Failure)): compatMessage[i] = ( message[i][0], _failureOldStyle(message[i][1])) client.callRemote('console', compatMessage) else: client.callRemote('console', message) except pb.ProtocolError: # Stale broker. self.detached(client, None)
def testIllegalInboxRename(self): self.stashed = None def login(): return self.client.login('testuser', 'password-test') def rename(): return self.client.rename('inbox', 'frotz') def stash(stuff): self.stashed = stuff d1 = self.connected.addCallback(strip(login)) d1.addCallbacks(strip(rename), self._ebGeneral) d1.addBoth(stash) d1.addCallbacks(self._cbStopClient, self._ebGeneral) d2 = self.loopback() d = defer.gatherResults([d1, d2]) d.addCallback(lambda _: self.failUnless(isinstance(self.stashed, failure.Failure))) return d
def test_client_connection_failed(self): """ Verify that connection failed causes the connection object to close. """ exc = Exception('a test') self.obj_ut.clientConnectionFailed(None, Failure(exc)) self.mock_connection.defunct.assert_called_with(exc)
def test_client_connection_lost(self): """ Verify that connection lost causes the connection object to close. """ exc = Exception('a test') self.obj_ut.clientConnectionLost(None, Failure(exc)) self.mock_connection.defunct.assert_called_with(exc)
def process(self): """Process an incoming request to the Farfetchd server.""" # Get site from channel self.site = self.channel.site # Set various default headers self.setHeader(b"Content-Type", b"application/vnd.api+json") self.setHeader(b"Server", "Farfetchd v%s" % FARFETCHD_API_VERSION) self.setHeader(b"Date", http.datetimeToString()) # Resource Identification self.prepath = [] self.postpath = list(map(http.unquote, self.path[1:].split(b'/'))) log.msg("postpath is %s" % self.postpath) log.msg("self.resource is %s" % self.resource) #requested_resource = self.resource.getChildForRequest(self) requested_resource = resource.getChildForRequest(self.resource, self) try: requested_resource = self.site.getResourceFor(self) #self.render(requested_resource) log.msg("Requested resource is %s" % requested_resource) log.msg("Requested resource entities are %s" % requested_resource.listEntities()) if requested_resource: if requested_resource.responseType: log.msg("Request will be handled by %r" % requested_resource.__class__.__name__) self.checkRequestHeaders() #requested_resource.render(self) self.render(requested_resource) else: self.setResponseCode(http.NOT_FOUND) self.write(b"No such resource") except: self.processingFailed(failure.Failure()) if not self.finished: self.finish()
def clientConnectionFailed(self, connector, reason): self.deferred.errback(Failure('Connection failed. Reason: %s' % reason))
def onClientMsg(self, msg, extra=None): if isinstance(msg, Failure): msg = msg.getErrorMessage() self.GetStatusBar().SetStatusText(msg)
def _invoke_callback(self, fd, events): if fd not in self._fds: return (reader, writer) = self._fds[fd] if reader: err = None if reader.fileno() == -1: err = error.ConnectionLost() elif events & IOLoop.READ: err = log.callWithLogger(reader, reader.doRead) if err is None and events & IOLoop.ERROR: err = error.ConnectionLost() if err is not None: self.removeReader(reader) reader.readConnectionLost(failure.Failure(err)) if writer: err = None if writer.fileno() == -1: err = error.ConnectionLost() elif events & IOLoop.WRITE: err = log.callWithLogger(writer, writer.doWrite) if err is None and events & IOLoop.ERROR: err = error.ConnectionLost() if err is not None: self.removeWriter(writer) writer.writeConnectionLost(failure.Failure(err))
def resolve(self, host, port, family=0): # getHostByName doesn't accept IP addresses, so if the input # looks like an IP address just return it immediately. if twisted.internet.abstract.isIPAddress(host): resolved = host resolved_family = socket.AF_INET elif twisted.internet.abstract.isIPv6Address(host): resolved = host resolved_family = socket.AF_INET6 else: deferred = self.resolver.getHostByName(utf8(host)) resolved = yield gen.Task(deferred.addBoth) if isinstance(resolved, failure.Failure): resolved.raiseException() elif twisted.internet.abstract.isIPAddress(resolved): resolved_family = socket.AF_INET elif twisted.internet.abstract.isIPv6Address(resolved): resolved_family = socket.AF_INET6 else: resolved_family = socket.AF_UNSPEC if family != socket.AF_UNSPEC and family != resolved_family: raise Exception('Requested socket family %d but got %d' % (family, resolved_family)) result = [ (resolved_family, (resolved, port)), ] raise gen.Return(result)
def clientConnectionLost(self, connector, reason): if isinstance(reason, failure.Failure): if reason.type == twisted.internet.error.ConnectionDone: logger.info("remote server closed connection") else: logger.info("remote server connection lost, reason: %r" % reason) self.owner.close()
def _cbIdent(self, ident, chatui): if not ident: print 'falsely identified.' return self._ebConnected(Failure(Exception("username or password incorrect"))) print 'Identified!' dl = [] for handlerClass, sname, pname in self.services: d = defer.Deferred() dl.append(d) handler = handlerClass(self, sname, pname, chatui, d) ident.callRemote('attach', sname, pname, handler).addCallback(handler.connected) return defer.DeferredList(dl)
def runTest(self): packets=["FLAPON\r\n\r\n",\ flap(1,"\000\000\000\001\000\001\000\004test"),\ flap(2,"toc_signon null 9999 test 0x100000 english \"penguin 0.1\"\000"),\ flap(2,"toc_init_done\000"),\ flap(2,"toc_send_im test hi\000")] shouldbe=[[1,"\000\000\000\001"],\ [2,"SIGN_ON:TOC1.0\000"],\ [2,"NICK:test\000"],\ [2,"CONFIG:\000"],\ [2,"IM_IN:test:F:hi\000"]] data="" for i in packets: data=data+i s=StringIOWithoutClosing() d=DummyTOC() fac=toc.TOCFactory() d.factory=fac d.makeConnection(protocol.FileWrapper(s)) d.dataReceived(data) d.connectionLost(failure.Failure(main.CONNECTION_DONE)) value=s.getvalue() flaps=[] f,value=readFlap(value) while f: flaps.append(f) f,value=readFlap(value) if flaps!=shouldbe: for i in range(len(flaps)): if flaps[i]!=shouldbe[i]:raise AssertionError("MultiPacketTest Failed!\nactual:%s\nshould be:%s"%(flaps[i],shouldbe[i])) raise AssertionError("MultiPacketTest Failed with incorrect length!, printing both lists\nactual:%s\nshould be:%s"%(flaps,shouldbe))