我们从Python开源项目中,提取了以下32个代码示例,用于说明如何使用twisted.internet.error.ConnectionRefusedError()。
def testReconnect(self): f = ClosingFactory() p = reactor.listenTCP(0, f, interface="127.0.0.1") n = p.getHost().port self.ports.append(p) f.port = p factory = MyClientFactory() d = loopUntil(lambda :p.connected) def step1(ignored): def clientConnectionLost(c, reason): c.connect() factory.clientConnectionLost = clientConnectionLost reactor.connectTCP("127.0.0.1", n, factory) return loopUntil(lambda :factory.failed) def step2(ignored): p = factory.protocol self.assertEquals((p.made, p.closed), (1, 1)) factory.reason.trap(error.ConnectionRefusedError) self.assertEquals(factory.stopped, 1) return self.cleanPorts(*self.ports) return d.addCallback(step1).addCallback(step2)
def test_update_broker_state(self, collected_hosts): """ test_update_broker_state Make sure that the client logs when a broker changes state """ client = KafkaClient(hosts=['broker_1:4567', 'broker_2', 'broker_3:45678']) collected_hosts.return_value = [('broker_1', 4567), ('broker_2', 9092), ('broker_3', 45678)] e = ConnectionRefusedError() bkr = "aBroker" client.reset_all_metadata = MagicMock() client.load_metadata_for_topics = MagicMock() client._collect_hosts_d = None client._update_broker_state(bkr, False, e) client.reset_all_metadata.assert_called_once_with() client.load_metadata_for_topics.assert_called_once_with()
def test_connect_error(self, *args): ''' Ensure the runner doesn't swallow errors and that it exits the reactor properly if there is one. ''' try: from autobahn.twisted.wamp import ApplicationRunner from twisted.internet.error import ConnectionRefusedError # the 'reactor' member doesn't exist until we import it from twisted.internet import reactor # noqa: F401 except ImportError: raise unittest.SkipTest('No twisted') runner = ApplicationRunner(u'ws://localhost:1', u'realm') exception = ConnectionRefusedError("It's a trap!") with patch('twisted.internet.reactor', FakeReactor(exception)) as mockreactor: self.assertRaises( ConnectionRefusedError, # pass a no-op session-creation method runner.run, lambda _: None, start_reactor=True ) self.assertTrue(mockreactor.stop_called)
def test_connectionFailed(self): """ If a connection cannot be established, the L{Deferred} returned by L{SSHCommandClientEndpoint.connect} fires with a L{Failure} representing the reason for the connection setup failure. """ endpoint = SSHCommandClientEndpoint.newConnection( self.reactor, b"/bin/ls -l", b"dummy user", self.hostname, self.port, knownHosts=self.knownHosts, ui=FixedResponseUI(False)) factory = Factory() factory.protocol = Protocol d = endpoint.connect(factory) factory = self.reactor.tcpClients[0][2] factory.clientConnectionFailed(None, Failure(ConnectionRefusedError())) self.failureResultOf(d).trap(ConnectionRefusedError)
def test_onlyRetryIfNoResponseReceived(self): """ Only L{RequestNotSent}, L{RequestTransmissionFailed} and L{ResponseNeverReceived} exceptions cause a retry. """ pool = client.HTTPConnectionPool(None) connection = client._RetryingHTTP11ClientProtocol(None, pool) self.assertTrue(connection._shouldRetry( b"GET", RequestNotSent(), None)) self.assertTrue(connection._shouldRetry( b"GET", RequestTransmissionFailed([]), None)) self.assertTrue(connection._shouldRetry( b"GET", ResponseNeverReceived([]),None)) self.assertFalse(connection._shouldRetry( b"GET", ResponseFailed([]), None)) self.assertFalse(connection._shouldRetry( b"GET", ConnectionRefusedError(), None))
def test_directConnectionLostCall(self): """ If C{connectionLost} is called directly on a port object, it succeeds (and doesn't expect the presence of a C{deferred} attribute). C{connectionLost} is called by L{reactor.disconnectAll} at shutdown. """ serverFactory = MyServerFactory() port = reactor.listenTCP(0, serverFactory, interface="127.0.0.1") portNumber = port.getHost().port port.connectionLost(None) client = MyClientFactory() serverFactory.protocolConnectionMade = defer.Deferred() client.protocolConnectionMade = defer.Deferred() reactor.connectTCP("127.0.0.1", portNumber, client) def check(ign): client.reason.trap(error.ConnectionRefusedError) return client.failDeferred.addCallback(check)
def connect(self): host = self.host port = self.port spec = self.spec user = self.username password = self.password vhost = self.vhost delegate = TwistedDelegate() onConn = Deferred() p = AMQClient(delegate, vhost, txamqp.spec.load(spec), heartbeat=0) f = protocol._InstanceFactory(reactor, p, onConn) c = reactor.connectTCP(host, port, f) def errb(thefailure): thefailure.trap(error.ConnectionRefusedError) logging.error(traceback.format_exc()) onConn.addErrback(errb) client = yield onConn self.client = client yield self.authenticate(self.client, user, password) returnValue(client)
def result_errmsg(result): """Return a useful error message string given a twisted errBack result.""" try: from pywbem.cim_operations import CIMError if result.type == ConnectionRefusedError: return 'connection refused. Check IP and zWBEMPort' elif result.type == TimeoutError: return 'connection timeout. Check IP and zWBEMPort' elif result.type == CIMError: if '401' in result.value.args[1]: return 'login failed. Check zWBEMUsername and zWBEMPassword' else: return result.value.args[1] else: return result.getErrorMessage() except AttributeError: pass return str(result)
def test_storage_dir_provided(self): """ When the program is run with an argument, it should start up and run. The program is expected to fail because it is unable to connect to Marathon. This test takes a while because we have to let txacme go through it's initial sync (registration + issuing of 0 certificates) before things can be halted. """ temp_dir = self.useFixture(TempDir()) yield main(reactor, raw_args=[ temp_dir.path, '--acme', LETSENCRYPT_STAGING_DIRECTORY.asText(), '--marathon', 'http://localhost:28080' # An address we can't reach ]) # Expect a 'certs' directory to be created self.assertThat(os.path.isdir(temp_dir.join('certs')), Equals(True)) # Expect a default certificate to be created self.assertThat(os.path.isfile(temp_dir.join('default.pem')), Equals(True)) # Expect to be unable to connect to Marathon flush_logged_errors(ConnectionRefusedError)
def testFailing(self): clientF = MyClientFactory() # XXX we assume no one is listening on TCP port 69 reactor.connectTCP("127.0.0.1", 69, clientF, timeout=5) def check(ignored): clientF.reason.trap(error.ConnectionRefusedError) return clientF.failDeferred.addCallback(check)
def connectionRefused(self): if self.startedDeferred is not None: d, self.startedDeferred = self.startedDeferred, None d.errback(error.ConnectionRefusedError("yup")) self.refused = 1
def connect(self, host=None, port=None, spec=None, user=None, password=None, vhost=None, heartbeat=None, clientClass=None): host = host or self.host port = port or self.port spec = spec or self.spec user = user or self.user password = password or self.password vhost = vhost or self.vhost heartbeat = heartbeat or self.heartbeat clientClass = clientClass or self.clientClass delegate = TestDelegate() on_connect = Deferred() p = clientClass(delegate, vhost, txamqp.spec.load(spec), heartbeat=heartbeat) f = protocol._InstanceFactory(reactor, p, on_connect) c = reactor.connectTCP(host, port, f) def errb(thefailure): thefailure.trap(error.ConnectionRefusedError) print("failed to connect to host: %s, port: %s; These tests are designed to run against a running instance" \ " of the %s AMQP broker on the given host and port. failure: %r" % (host, port, self.broker, thefailure,)) thefailure.raiseException() on_connect.addErrback(errb) self.connectors.append(c) client = yield on_connect yield self.authenticate(client, user, password) returnValue(client)
def _handle_error(self, failure): """Handle errors in connecting or resolving.""" log.err(failure) error_code = 1 if failure.check(DNSLookupError): error_code = 4 if failure.check(ConnectionRefusedError): error_code = 5 self._write_response(error_code, "0.0.0.0", 0)
def failed(self, failure, job_id): if failure.check(CancelledError): self.job_failed("Response max size exceeded! job id: %s!" % job_id, job_id) elif failure.check(InvalidResponseRetry): ex = failure.value if job_id in self.retry_counter and self.retry_counter[job_id] == self.max_retry: self.job_failed("Max retry has been reached! job id: %s!" % job_id, job_id) else: self.job_failed_retry(ex.message, job_id) elif failure.check(ResponseNeverReceived): self.job_failed("No response from the server! job id: %s!" % job_id, job_id) elif failure.check(ResponseFailed): # @TODO add retry self.job_failed("Connection to server failed, retry .... %s!" % job_id, job_id) elif failure.check(NoResponseContent): self.job_failed("Response has no content .... %s!" % job_id, job_id) elif failure.check(TimeoutError): if job_id in self.retry_counter and self.retry_counter[job_id] == self.max_retry: self.job_failed("Max retry has been reached! job id: %s!" % job_id, job_id) else: self.job_failed_retry("Request timeout .... %s!" % job_id, job_id) elif failure.check(ConnectionRefusedError): if job_id in self.retry_counter and self.retry_counter[job_id] == self.max_retry: self.job_failed("Max retry has been reached! job id: %s!" % job_id, job_id) else: self.job_failed_retry("Connection refused .... %s!" % job_id, job_id) else: ex = failure.value self.job_failed("No proper failure found: %s, \n %s!" % (job_id, ex.message), job_id) failure.printTraceback()
def failed(self, failure): if failure.check(ChannelClosed): self.retry_connect() elif failure.check(ConnectionClosed) or failure.check(ConnectionRefusedError): self.retry_connect() else: log.err("Unhandled failure in Amqp Service....") failure.printTraceback() reactor.stop()
def connect(self, on_connect, on_disconnect=None, on_event=None): """Connect to QTM :param on_connect: Called on successful connection to QTM. Callback receives an :class:`QRTConnection` object. :param on_disconnect: Called if connection fails or when connection is lost. :param on_event: Called when there's an event from QTM. """ point = TCP4ClientEndpoint(reactor, self.host, self.port) factory = QRTFactory(self.version, on_disconnect, on_event, self.logger) try: p = yield point.connect(factory) except ConnectionRefusedError as reason: if on_disconnect: on_disconnect(QRTCommandException(str(reason))) return except Exception as reason: if on_disconnect: on_disconnect(reason) return try: version = yield p.connected_d except Exception as reason: if on_disconnect: p.on_disconnect = None p.transport.loseConnection() on_disconnect(reason) return on_connect(QRTConnection(p), version)
def test_connectionFailed(self): """ The L{Deferred} returned by L{Agent.request} fires with a L{Failure} if the TCP connection attempt fails. """ result = self.agent.request(b'GET', b'http://foo/') # Cause the connection to be refused host, port, factory = self.reactor.tcpClients.pop()[:3] factory.clientConnectionFailed(None, Failure(ConnectionRefusedError())) self.reactor.advance(10) # ^ https://twistedmatrix.com/trac/ticket/8202 self.failureResultOf(result, ConnectionRefusedError)
def test_errno(self): """ L{error.getConnectError} converts based on errno for C{socket.error}. """ self.assertErrnoException(errno.ENETUNREACH, error.NoRouteError) self.assertErrnoException(errno.ECONNREFUSED, error.ConnectionRefusedError) self.assertErrnoException(errno.ETIMEDOUT, error.TCPTimedOutError) if platformType == "win32": self.assertErrnoException(errno.WSAECONNREFUSED, error.ConnectionRefusedError) self.assertErrnoException(errno.WSAENETUNREACH, error.NoRouteError)
def test_connectionRefused(self): """ A L{ConnectionRefusedError} exception is raised when a connection attempt is actively refused by the other end. Note: This test assumes no one is listening on port 80 UDP. """ client = GoodClient() clientStarted = client.startedDeferred = defer.Deferred() port = reactor.listenUDP(0, client, interface="127.0.0.1") server = Server() serverStarted = server.startedDeferred = defer.Deferred() port2 = reactor.listenUDP(0, server, interface="127.0.0.1") d = defer.DeferredList( [clientStarted, serverStarted], fireOnOneErrback=True) def cbStarted(ignored): connectionRefused = client.startedDeferred = defer.Deferred() client.transport.connect("127.0.0.1", 80) for i in range(10): client.transport.write(intToBytes(i)) server.transport.write(intToBytes(i), ("127.0.0.1", 80)) return self.assertFailure( connectionRefused, error.ConnectionRefusedError) d.addCallback(cbStarted) def cbFinished(ignored): return defer.DeferredList([ defer.maybeDeferred(port.stopListening), defer.maybeDeferred(port2.stopListening)], fireOnOneErrback=True) d.addCallback(cbFinished) return d
def test_loginConnectionRefused(self): """ L{PBClientFactory.login} returns a L{Deferred} which is errbacked with the L{ConnectionRefusedError} if the underlying connection is refused. """ clientFactory = pb.PBClientFactory() loginDeferred = clientFactory.login( credentials.UsernamePassword(b"foo", b"bar")) clientFactory.clientConnectionFailed( None, failure.Failure( ConnectionRefusedError("Test simulated refused connection"))) return self.assertFailure(loginDeferred, ConnectionRefusedError)
def test_hello_world(self): def got_response(response): print "Got this data %s" % response def connection_failed(failure): failure.trap(ConnectionRefusedError) print "Connection Refused" self.address = "127.0.0.1" self.port = 57002 payload = "Hello World!\n\r" d = self.sendPayload(payload) d.addErrback(connection_failed) d.addCallback(got_response) return d
def createReport(self): """ Creates a report on the oonib collector. """ log.msg("Creating report with OONIB Reporter. Please be patient.") log.msg("This may take up to 1-2 minutes...") try: response = yield self.collector_client.createReport( self.testDetails ) except ConnectionRefusedError: log.err("Connection to reporting backend failed " "(ConnectionRefusedError)") raise errors.OONIBReportCreationError except errors.HostUnreachable: log.err("Host is not reachable (HostUnreachable error") raise errors.OONIBReportCreationError except (errors.OONIBInvalidInputHash, errors.OONIBInvalidNettestName): log.err("The specified input or nettests cannot be submitted to " "this collector.") log.msg("Try running a different test or try reporting to a " "different collector.") raise errors.OONIBReportCreationError except errors.OONIBError: log.err("Failed to connect to reporter backend") raise errors.OONIBReportCreationError except Exception as exc: log.err("Failed to connect to reporter backend") log.exception(exc) raise errors.OONIBReportCreationError self.reportId = response['report_id'].encode('ascii') self.backendVersion = response['backend_version'] self.supportedFormats = response.get('supported_formats', ["yaml"]) log.debug("Created report with id %s" % response['report_id']) defer.returnValue(response['report_id'])
def test_connectionRefused(self): """ Test that using the connected UDP API will deliver connection refused notification when packets are sent to an address at which no one is listening. """ # XXX - assume no one listening on port 80 UDP client = Client() clientStarted = client.startedDeferred = Deferred() server = Server() serverStarted = server.startedDeferred = Deferred() started = gatherResults([clientStarted, serverStarted]) clientPort = reactor.connectUDP("127.0.0.1", 80, client) serverPort = reactor.listenUDP(0, server, interface="127.0.0.1") def cbStarted(ignored): clientRefused = client.startedDeferred = Deferred() client.transport.write("a") client.transport.write("b") server.transport.write("c", ("127.0.0.1", 80)) server.transport.write("d", ("127.0.0.1", 80)) server.transport.write("e", ("127.0.0.1", 80)) c = clientPort.getHost() s = serverPort.getHost() server.transport.write("toserver", (s.host, s.port)) server.transport.write("toclient", (c.host, c.port)) return self.assertFailure(clientRefused, error.ConnectionRefusedError) started.addCallback(cbStarted) def cleanup(passthrough): result = gatherResults([ maybeDeferred(clientPort.stopListening), maybeDeferred(serverPort.stopListening)]) result.addCallback(lambda ign: passthrough) return result started.addBoth(cleanup) return started