Python twisted.internet.error.ConnectionRefusedError() Examples

The following are 30 code examples of twisted.internet.error.ConnectionRefusedError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module twisted.internet.error , or try the search function .
Example #1
Source File: test_brokerclient.py    From afkak with Apache License 2.0 6 votes vote down vote up
def test_updateMetadata_retry(self):
        """
        Updating the broker metadata of the client changes the destination of
        the next connection attempt. Any outstanding connections remain until
        then.
        """
        d = self.brokerClient.makeRequest(1, METADATA_REQUEST_1)
        self.assertNoResult(d)
        self.assertEqual([('host', 1234)], self.connections.calls)

        self.brokerClient.updateMetadata(BrokerMetadata(node_id=1, host='other', port=2345))
        self.assertEqual('other', self.brokerClient.host)
        self.assertEqual(2345, self.brokerClient.port)
        # A connection to the new host was *not* triggered.
        self.assertEqual([('host', 1234)], self.connections.calls)

        # Fail the pending connection:
        self.connections.fail('host', ConnectionRefusedError("Nope."))
        # Trigger retry attempt, which happens after a delay:
        self.reactor.advance(self.retryDelay)

        # The retry attempt was made to the new host.
        self.assertEqual([('host', 1234), ('other', 2345)], self.connections.calls) 
Example #2
Source File: test_endpoints.py    From learn_python3_spider with MIT License 6 votes vote down vote up
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) 
Example #3
Source File: test_agent.py    From learn_python3_spider with MIT License 6 votes vote down vote up
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)) 
Example #4
Source File: test_tcp.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_reconnect(self):
        """
        Calling L{IConnector.connect} in C{Factory.clientConnectionLost} causes
        a new connection attempt to be made.
        """
        serverFactory = ClosingFactory()
        tcpPort = reactor.listenTCP(0, serverFactory, interface="127.0.0.1")
        serverFactory.port = tcpPort
        self.addCleanup(serverFactory.cleanUp)
        portNumber = tcpPort.getHost().port

        clientFactory = MyClientFactory()

        def clientConnectionLost(connector, reason):
            connector.connect()
        clientFactory.clientConnectionLost = clientConnectionLost
        reactor.connectTCP("127.0.0.1", portNumber, clientFactory)

        d = loopUntil(lambda: clientFactory.failed)
        def reconnectFailed(ignored):
            p = clientFactory.protocol
            self.assertEqual((p.made, p.closed), (1, 1))
            clientFactory.reason.trap(error.ConnectionRefusedError)
            self.assertEqual(clientFactory.stopped, 1)
        return d.addCallback(reconnectFailed) 
Example #5
Source File: test_tcp.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #6
Source File: test_tcp.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
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) 
Example #7
Source File: test_cross_pod_scheduling.py    From ccs-calendarserver with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        """
        Setup fake hook-up between pods
        """
        @inlineCallbacks
        def _fakeSubmitRequest(iself, ssl, host, port, request):

            if self.refuseConnection:
                raise MultiFailure((Failure(ConnectionRefusedError()),))
            else:
                pod = (port - 8008) / 100
                inbox = IScheduleInboxResource(self.site.resource, self.theStoreUnderTest(pod), podding=True)
                response = yield inbox.http_POST(SimpleRequest(
                    self.site,
                    "POST",
                    "http://{host}:{port}/podding".format(host=host, port=port),
                    request.headers,
                    request.stream.mem,
                ))
                returnValue(response)

        self.refuseConnection = False
        self.patch(IScheduleRequest, "_submitRequest", _fakeSubmitRequest)
        yield super(TestCrossPodScheduling, self).setUp() 
Example #8
Source File: test_tcp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
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) 
Example #9
Source File: test_wormhole.py    From magic-wormhole with MIT License 6 votes vote down vote up
def test_all_deferreds(self):
        # point at a URL that will never connect
        port = allocate_tcp_port()
        w = wormhole.create(APPID, "ws://127.0.0.1:%d/v1" % port, reactor)
        # nothing is listening, but it will take a turn to discover that
        w.allocate_code()
        d1 = w.get_code()
        d2 = w.get_unverified_key()
        d3 = w.get_verifier()
        d4 = w.get_versions()
        d5 = w.get_message()
        yield self.assertSCE(d1, ConnectionRefusedError)
        yield self.assertSCE(d2, ConnectionRefusedError)
        yield self.assertSCE(d3, ConnectionRefusedError)
        yield self.assertSCE(d4, ConnectionRefusedError)
        yield self.assertSCE(d5, ConnectionRefusedError) 
Example #10
Source File: test_agent.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
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)) 
Example #11
Source File: test_clusterservice.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_update_connections_connect_error_is_logged_tersely(self):
        service = ClusterClientService(Clock())
        _make_connection = self.patch(service, "_make_connection")
        _make_connection.side_effect = error.ConnectionRefusedError()

        logger = self.useFixture(TwistedLoggerFixture())

        eventloops = {"an-event-loop": [("127.0.0.1", 1234)]}
        yield service._update_connections(eventloops)

        self.assertThat(
            _make_connection,
            MockCalledOnceWith("an-event-loop", ("::ffff:127.0.0.1", 1234)),
        )

        self.assertEqual(
            "Making connections to event-loops: an-event-loop\n"
            "---\n"
            "Event-loop an-event-loop (::ffff:127.0.0.1:1234): Connection "
            "was refused by other side.",
            logger.dump(),
        ) 
Example #12
Source File: test_cli.py    From magic-wormhole with MIT License 5 votes vote down vote up
def test_receiver(self):
        cfg = config("receive")
        cfg.hide_progress = True
        cfg.listen = False
        cfg.relay_url = self.relayurl
        cfg.transit_helper = ""
        cfg.stdout = io.StringIO()
        cfg.stderr = io.StringIO()

        cfg.code = u"1-abc"

        receive_d = cmd_receive.receive(cfg)
        e = yield self.assertFailure(receive_d, ServerConnectionError)
        self.assertIsInstance(e.reason, ConnectionRefusedError) 
Example #13
Source File: socks.py    From telepresence with Apache License 2.0 5 votes vote down vote up
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) 
Example #14
Source File: test_webclient.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
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('GET', 'http://foo/')

        # Cause the connection to be refused
        host, port, factory = self.reactor.tcpClients.pop()[:3]
        factory.clientConnectionFailed(None, Failure(ConnectionRefusedError()))
        self.completeConnection()

        return self.assertFailure(result, ConnectionRefusedError) 
Example #15
Source File: test_tcp.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
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) 
Example #16
Source File: test_udp.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def connectionRefused(self):
        if self.startedDeferred is not None:
            d, self.startedDeferred = self.startedDeferred, None
            d.errback(error.ConnectionRefusedError("yup"))
        self.refused = 1 
Example #17
Source File: socks5.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def handleCmdConnectFailure(self, failure):
        log.error("CMD CONNECT: %s" % failure.getErrorMessage())

        # Map common twisted errors to SOCKS error codes
        if failure.type == error.NoRouteError:
            self.sendReply(SOCKSv5Reply.NetworkUnreachable)
        elif failure.type == error.ConnectionRefusedError:
            self.sendReply(SOCKSv5Reply.ConnectionRefused)
        elif failure.type == error.TCPTimedOutError or failure.type == error.TimeoutError:
            self.sendReply(SOCKSv5Reply.TTLExpired)
        elif failure.type == error.UnsupportedAddressFamily:
            self.sendReply(SOCKSv5Reply.AddressTypeNotSupported)
        elif failure.type == error.ConnectError:
            # Twisted doesn't have a exception defined for EHOSTUNREACH,
            # so the failure is a ConnectError.  Try to catch this case
            # and send a better reply, but fall back to a GeneralFailure.
            reply = SOCKSv5Reply.GeneralFailure
            try:
                import errno
                if hasattr(errno, "EHOSTUNREACH"):
                    if failure.value.osError == errno.EHOSTUNREACH:
                        reply = SOCKSv5Reply.HostUnreachable
                if hasattr(errno, "WSAEHOSTUNREACH"):
                    if failure.value.osError == errno.WSAEHOSTUNREACH:
                        reply = SOCKSv5Reply.HostUnreachable
            except Exception:
                pass
            self.sendReply(reply)
        else:
            self.sendReply(SOCKSv5Reply.GeneralFailure)

        failure.trap(error.NoRouteError, error.ConnectionRefusedError,
                     error.TCPTimedOutError, error.TimeoutError,
                     error.UnsupportedAddressFamily, error.ConnectError) 
Example #18
Source File: test_cli.py    From magic-wormhole with MIT License 5 votes vote down vote up
def test_sender_allocation(self):
        cfg = config("send")
        cfg.hide_progress = True
        cfg.listen = False
        cfg.relay_url = self.relayurl
        cfg.transit_helper = ""
        cfg.stdout = io.StringIO()
        cfg.stderr = io.StringIO()

        cfg.text = "hi"

        send_d = cmd_send.send(cfg)
        e = yield self.assertFailure(send_d, ServerConnectionError)
        self.assertIsInstance(e.reason, ConnectionRefusedError) 
Example #19
Source File: test_udp.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def testConnectionRefused(self):
        # assume no one 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(str(i))
                server.transport.write(str(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 
Example #20
Source File: test_pb.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
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("foo", "bar"))
        clientFactory.clientConnectionFailed(
            None,
            failure.Failure(
                ConnectionRefusedError("Test simulated refused connection")))
        return self.assertFailure(loginDeferred, ConnectionRefusedError) 
Example #21
Source File: tuntap.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def write(self, datagram):
        """Write a datagram."""
#        header = makePacketInfo(0, 0)
        try:
            return os.write(self.fd, datagram)
        except IOError, e:
            if e.errno == errno.EINTR:
                return self.write(datagram)
            elif e.errno == errno.EMSGSIZE:
                raise error.MessageLengthError, "message too long"
            elif e.errno == errno.ECONNREFUSED:
                raise error.ConnectionRefusedError
            else:
                raise 
Example #22
Source File: test_tcp.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
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)
        start = time.time()
        def check(ignored):
            clientF.reason.trap(error.ConnectionRefusedError)
        return clientF.failDeferred.addCallback(check)
        #self.assert_(time.time() - start < 0.1) 
Example #23
Source File: test_udp.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def connectionRefused(self):
        if self.startedDeferred is not None:
            d, self.startedDeferred = self.startedDeferred, None
            d.errback(error.ConnectionRefusedError("yup"))
        self.refused = 1 
Example #24
Source File: test_udp.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def connectionRefused(self):
        if self.startedDeferred is not None:
            d, self.startedDeferred = self.startedDeferred, None
            d.errback(error.ConnectionRefusedError("yup"))
        self.refused = 1 
Example #25
Source File: test_udp.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def testConnectionRefused(self):
        # assume no one 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(str(i))
                server.transport.write(str(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 
Example #26
Source File: test_clusterservice.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_failed_update_is_logged(self):
        logger = self.useFixture(TwistedLoggerFixture())

        service = ClusterClientService(Clock())
        _doUpdate = self.patch(service, "_doUpdate")
        _doUpdate.side_effect = error.ConnectionRefusedError()

        # Starting the service causes the first update to be performed, which
        # will fail because of above.
        service.startService()
        self.assertThat(_doUpdate, MockCalledOnceWith())

        dump = logger.dump()
        self.assertIn("Connection was refused by other side.", dump) 
Example #27
Source File: test_clusterservice.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_update_connect_error_is_logged_tersely(self):
        mock_agent = MagicMock()
        mock_agent.request.side_effect = error.ConnectionRefusedError()
        self.patch(clusterservice, "Agent").return_value = mock_agent

        logger = self.useFixture(TwistedLoggerFixture())

        service = ClusterClientService(Clock())
        _get_config_rpc_info_urls = self.patch(
            service, "_get_config_rpc_info_urls"
        )
        _get_config_rpc_info_urls.return_value = ["http://127.0.0.1/MAAS"]
        _build_rpc_info_urls = self.patch(service, "_build_rpc_info_urls")
        _build_rpc_info_urls.return_value = succeed(
            [([b"http://[::ffff:127.0.0.1]/MAAS"], "http://127.0.0.1/MAAS")]
        )

        # Starting the service causes the first update to be performed.
        service.startService()

        self.assertThat(
            mock_agent.request,
            MockCalledOnceWith(
                b"GET",
                ascii_url("http://[::ffff:127.0.0.1]/MAAS"),
                Headers({"User-Agent": [ANY], "Host": ["127.0.0.1"]}),
            ),
        )
        dump = logger.dump()
        self.assertIn(
            "Region not available: Connection was refused by other side.", dump
        )
        self.assertIn("While requesting RPC info at", dump) 
Example #28
Source File: test_clusterservice.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_update_connect_includes_host(self):
        # Regression test for LP:1792462
        mock_agent = MagicMock()
        mock_agent.request.side_effect = error.ConnectionRefusedError()
        self.patch(clusterservice, "Agent").return_value = mock_agent

        service = ClusterClientService(Clock())
        fqdn = "%s.example.com" % factory.make_hostname()
        _get_config_rpc_info_urls = self.patch(
            service, "_get_config_rpc_info_urls"
        )
        _get_config_rpc_info_urls.return_value = ["http://%s/MAAS" % fqdn]
        _build_rpc_info_urls = self.patch(service, "_build_rpc_info_urls")
        _build_rpc_info_urls.return_value = succeed(
            [([b"http://[::ffff:127.0.0.1]/MAAS"], "http://%s/MAAS" % fqdn)]
        )

        # Starting the service causes the first update to be performed.
        service.startService()

        self.assertThat(
            mock_agent.request,
            MockCalledOnceWith(
                b"GET",
                ascii_url("http://[::ffff:127.0.0.1]/MAAS"),
                Headers({"User-Agent": [ANY], "Host": [fqdn]}),
            ),
        )

    # The following represents an example response from the RPC info
    # view in maasserver. Event-loops listen on ephemeral ports, and
    # it's up to the RPC info view to direct clients to them. 
Example #29
Source File: crawlera.py    From openslack-crawler with Apache License 2.0 5 votes vote down vote up
def process_exception(self, request, exception, spider):
        if not self._is_enabled_for_request(request):
            return
        if isinstance(exception, ConnectionRefusedError):
            # Handle crawlera downtime
            self._set_custom_delay(request, self.connection_refused_delay) 
Example #30
Source File: test_wormhole.py    From magic-wormhole with MIT License 5 votes vote down vote up
def test_no_connection(self):
        # point at a URL that will never connect
        port = allocate_tcp_port()
        w = wormhole.create(APPID, "ws://127.0.0.1:%d/v1" % port, reactor)
        # nothing is listening, but it will take a turn to discover that
        d1 = w.get_code()
        d2 = w.get_unverified_key()
        d3 = w.get_verifier()
        d4 = w.get_versions()
        d5 = w.get_message()
        yield self.assertSCE(d1, ConnectionRefusedError)
        yield self.assertSCE(d2, ConnectionRefusedError)
        yield self.assertSCE(d3, ConnectionRefusedError)
        yield self.assertSCE(d4, ConnectionRefusedError)
        yield self.assertSCE(d5, ConnectionRefusedError)