def test_restartAfterExcept(self):
        """
        Even if the server factory raise an exception in C{stopFactory}, the
        corresponding C{tcp.Port} instance should be in a sane state and can
        be restarted.
        """
        serverFactory = MyServerFactory()
        def raiseException():
            raise RuntimeError("An error")
        serverFactory.stopFactory = raiseException
        port = reactor.listenTCP(0, serverFactory, interface="127.0.0.1")
        self.addCleanup(port.stopListening)

        def cbStopListening(ignored):
            del serverFactory.stopFactory
            port.startListening()

            client = MyClientFactory()
            serverFactory.protocolConnectionMade = defer.Deferred()
            client.protocolConnectionMade = defer.Deferred()
            connector = reactor.connectTCP("127.0.0.1",
                                           port.getHost().port, client)
            self.addCleanup(connector.disconnect)
            return defer.gatherResults([serverFactory.protocolConnectionMade,
                                        client.protocolConnectionMade]
                ).addCallback(close)

        def close(result):
            serverProto, clientProto = result
            clientProto.transport.loseConnection()
            serverProto.transport.loseConnection()

        return self.assertFailure(port.stopListening(), RuntimeError
            ).addCallback(cbStopListening)

        Even if the server factory raise an exception in C{stopFactory}, the
        corresponding C{tcp.Port} instance should be in a sane state and can
        be restarted.
        
stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_tcp.py