'Full test using a custom server limiting number of connections.'

def test_limit(self):

    server = Server()
    (c1, c2, c3, c4) = [SimpleProtocol() for i in range(4)]
    tServer = policies.ThrottlingFactory(server, 2)
    wrapTServer = WrappingFactory(tServer)
    wrapTServer.deferred = defer.Deferred()
    p = reactor.listenTCP(0, wrapTServer, interface='127.0.0.1')
    n = p.getHost().port
    def _connect123(results):
        reactor.connectTCP('127.0.0.1', n, SillyFactory(c1))
        c1.dConnected.addCallback((lambda r: reactor.connectTCP('127.0.0.1', n, SillyFactory(c2))))
        c2.dConnected.addCallback((lambda r: reactor.connectTCP('127.0.0.1', n, SillyFactory(c3))))
        return c3.dDisconnected
    def _check123(results):
        self.assertEqual([c.connected for c in (c1, c2, c3)], [1, 1, 1])
        self.assertEqual([c.disconnected for c in (c1, c2, c3)], [0, 0, 1])
        self.assertEqual(len(tServer.protocols.keys()), 2)
        return results
    def _lose1(results):
        c1.transport.loseConnection()
        return c1.dDisconnected
    def _connect4(results):
        reactor.connectTCP('127.0.0.1', n, SillyFactory(c4))
        return c4.dConnected
    def _check4(results):
        self.assertEqual(c4.connected, 1)
        self.assertEqual(c4.disconnected, 0)
        return results
    def _cleanup(results):
        for c in (c2, c4):
            c.transport.loseConnection()
        return defer.DeferredList([defer.maybeDeferred(p.stopListening), c2.dDisconnected, c4.dDisconnected])
    wrapTServer.deferred.addCallback(_connect123)
    wrapTServer.deferred.addCallback(_check123)
    wrapTServer.deferred.addCallback(_lose1)
    wrapTServer.deferred.addCallback(_connect4)
    wrapTServer.deferred.addCallback(_check4)
    wrapTServer.deferred.addCallback(_cleanup)
    return wrapTServer.deferred
