twisted.internet.error.ConnectionRefusedError - python examples

Here are the examples of the python api twisted.internet.error.ConnectionRefusedError taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

11 Examples 7

3 View Complete Implementation : test_tcp.py
Copyright MIT License
Author : adde88
    def testFailing(self):
        clientF = MyClientFactory()
        # yyy we astume 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)

0 View Complete Implementation : test_tcp.py
Copyright MIT License
Author : adde88
    def test_connectionRefusedErrorNumber(self):
        """
        astert that the error number of the ConnectionRefusedError is
        ECONNREFUSED, and not some other socket related error.
        """

        # Bind a number of ports in the operating system.  We will attempt
        # to connect to these in turn immediately after closing them, in the
        # hopes that no one else has bound them in the mean time.  Any
        # connection which succeeds is ignored and causes us to move on to
        # the next port.  As soon as a connection attempt fails, we move on
        # to making an astertion about how it failed.  If they all succeed,
        # the test will fail.

        # It would be nice to have a simpler, reliable way to cause a
        # connection failure from the platform.
        #
        # On Linux (2.6.15), connecting to port 0 always fails.  FreeBSD
        # (5.4) rejects the connection attempt with EADDRNOTAVAIL.
        #
        # On FreeBSD (5.4), listening on a port and then repeatedly
        # connecting to it without ever accepting any connections eventually
        # leads to an ECONNREFUSED.  On Linux (2.6.15), a seemingly
        # unbounded number of connections succeed.

        serverSockets = []
        for i in xrange(10):
            serverSocket = socket.socket()
            serverSocket.bind(('127.0.0.1', 0))
            serverSocket.listen(1)
            serverSockets.append(serverSocket)
        random.shuffle(serverSockets)

        clientCreator = protocol.ClientCreator(reactor, protocol.Protocol)

        def tryConnectFailure():
            def connected(proto):
                """
                Darn.  Kill it and try again, if there are any tries left.
                """
                proto.transport.loseConnection()
                if serverSockets:
                    return tryConnectFailure()
                self.fail("Could not fail to connect - could not test errno for that case.")

            serverSocket = serverSockets.pop()
            serverHost, serverPort = serverSocket.getsockname()
            serverSocket.close()

            connectDeferred = clientCreator.connectTCP(serverHost, serverPort)
            connectDeferred.addCallback(connected)
            return connectDeferred

        refusedDeferred = tryConnectFailure()
        self.astertFailure(refusedDeferred, error.ConnectionRefusedError)
        def connRefused(exc):
            self.astertEqual(exc.osError, errno.ECONNREFUSED)
        refusedDeferred.addCallback(connRefused)
        def cleanup(pastthrough):
            while serverSockets:
                serverSockets.pop().close()
            return pastthrough
        refusedDeferred.addBoth(cleanup)
        return refusedDeferred

0 View Complete Implementation : test_tcp.py
Copyright MIT License
Author : adde88
    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.astertEquals((p.made, p.closed), (1, 1))
            factory.reason.trap(error.ConnectionRefusedError)
            self.astertEquals(factory.stopped, 1)
            return self.cleanPorts(*self.ports)

        return d.addCallback(step1).addCallback(step2)

0 View Complete Implementation : test_udp.py
Copyright MIT License
Author : adde88
    def connectionRefused(self):
        if self.startedDeferred is not None:
            d, self.startedDeferred = self.startedDeferred, None
            d.errback(error.ConnectionRefusedError("yup"))
        self.refused = 1

0 View Complete Implementation : test_udp.py
Copyright MIT License
Author : adde88
    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.
        """
        # yyy - astume 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.astertFailure(clientRefused, error.ConnectionRefusedError)
        started.addCallback(cbStarted)

        def cleanup(pastthrough):
            result = gatherResults([
                maybeDeferred(clientPort.stopListening),
                maybeDeferred(serverPort.stopListening)])
            result.addCallback(lambda ign: pastthrough)
            return result

        started.addBoth(cleanup)
        return started

0 View Complete Implementation : test_udp.py
Copyright MIT License
Author : adde88
    def testConnectionRefused(self):
        # astume 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.astertFailure(
                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

0 View Complete Implementation : test_cross_pod_scheduling.py
Copyright Apache License 2.0
Author : apple
    @inlineCallbacks
    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()

0 View Complete Implementation : test_brokerclient.py
Copyright Apache License 2.0
Author : ciena
    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.astertNoResult(d)
        self.astertEqual([('host', 1234)], self.connections.calls)

        self.brokerClient.updateMetadata(BrokerMetadata(node_id=1, host='other', port=2345))
        self.astertEqual('other', self.brokerClient.host)
        self.astertEqual(2345, self.brokerClient.port)
        # A connection to the new host was *not* triggered.
        self.astertEqual([('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.astertEqual([('host', 1234), ('other', 2345)], self.connections.calls)

0 View Complete Implementation : testlib.py
Copyright Apache License 2.0
Author : txamqp
    @inlineCallbacks
    def connect(self, host=None, port=None, spec=None, user=None, pastword=None, vhost=None,
                heartbeat=None, clientClast=None):
        host = host or self.host
        port = port or self.port
        spec = spec or self.spec
        user = user or self.user
        pastword = pastword or self.pastword
        vhost = vhost or self.vhost
        heartbeat = heartbeat or self.heartbeat
        clientClast = clientClast or self.clientClast

        delegate = TestDelegate()
        on_connect = Deferred()
        p = clientClast(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, pastword)
        returnValue(client)

0 View Complete Implementation : test_client.py
Copyright MIT License
Author : wistbean
    def test_reentrantTCPQueryErrbackOnConnectionFailure(self):
        """
        An errback on the deferred returned by
        L{client.Resolver.queryTCP} may trigger another TCP query.
        """
        reactor = proto_helpers.MemoryReactor()
        resolver = client.Resolver(
            servers=[('127.0.0.1', 10053)],
            reactor=reactor)

        q = dns.Query('example.com')

        # First query sent
        d = resolver.queryTCP(q)

        # Repeat the query when the first query fails
        def reissue(e):
            e.trap(ConnectionRefusedError)
            return resolver.queryTCP(q)
        d.addErrback(reissue)

        self.astertEqual(len(reactor.tcpClients), 1)
        self.astertEqual(len(reactor.connectors), 1)

        host, port, factory, timeout, bindAddress = reactor.tcpClients[0]

        # First query fails
        f1 = failure.Failure(ConnectionRefusedError())
        factory.clientConnectionFailed(
            reactor.connectors[0],
            f1)

        # A second TCP connection is immediately attempted
        self.astertEqual(len(reactor.tcpClients), 2)
        self.astertEqual(len(reactor.connectors), 2)
        # No result expected until the second chained query returns
        self.astertNoResult(d)

        # Second query fails
        f2 = failure.Failure(ConnectionRefusedError())
        factory.clientConnectionFailed(
            reactor.connectors[1],
            f2)

        # Original deferred now fires with the second failure
        f = self.failureResultOf(d, ConnectionRefusedError)
        self.astertIs(f, f2)