'Test that lost connections properly have their underlying socket
resources cleaned up.'

def test_properlyCloseFiles(self):

    onServerConnectionLost = defer.Deferred()
    serverFactory = protocol.ServerFactory()
    serverFactory.protocol = (lambda : ConnectionLostNotifyingProtocol(onServerConnectionLost))
    serverPort = self.createServer('127.0.0.1', 0, serverFactory)
    onClientConnectionLost = defer.Deferred()
    serverAddr = serverPort.getHost()
    clientCreator = protocol.ClientCreator(reactor, (lambda : HandleSavingProtocol(onClientConnectionLost)))
    clientDeferred = self.connectClient(serverAddr.host, serverAddr.port, clientCreator)
    def clientConnected(client):
        '\n                                                Disconnect    the    client.        Return    a    Deferred    which    fires    when    both\n                                                the    client    and    the    server    have    received    disconnect    notification.\n                                                '
        client.transport.write('some    bytes    to    make    sure    the    connection    is    set    up')
        client.transport.loseConnection()
        return defer.gatherResults([onClientConnectionLost, onServerConnectionLost])
    clientDeferred.addCallback(clientConnected)
    def clientDisconnected(result):
        '\n                                                Verify    that    the    underlying    platform    socket    handle    has    been\n                                                cleaned    up.\n                                                '
        (client, server) = result
        if (not client.lostConnectionReason.check(error.ConnectionClosed)):
            err(client.lostConnectionReason, 'Client    lost    connection    for    unexpected    reason')
        if (not server.lostConnectionReason.check(error.ConnectionClosed)):
            err(server.lostConnectionReason, 'Server    lost    connection    for    unexpected    reason')
        expectedErrorCode = self.getHandleErrorCode()
        exception = self.assertRaises(self.getHandleExceptionType(), client.handle.send, 'bytes')
        self.assertEqual(exception.args[0], expectedErrorCode)
    clientDeferred.addCallback(clientDisconnected)
    def cleanup(passthrough):
        '\n                                                Shut    down    the    server    port.        Return    a    Deferred    which    fires    when\n                                                this    has    completed.\n                                                '
        result = defer.maybeDeferred(serverPort.stopListening)
        result.addCallback((lambda ign: passthrough))
        return result
    clientDeferred.addBoth(cleanup)
    return clientDeferred
