Exemple #1
0
class LoopbackUNIXTests(LoopbackTestCaseMixin, unittest.TestCase):
    loopbackFunc = staticmethod(loopback.loopbackUNIX)

    if interfaces.IReactorUNIX(reactor, None) is None:
        skip = "Current reactor does not support UNIX sockets"
    elif _PY3:
        skip = "UNIX sockets not supported on Python 3.  See #6136"
    def testUNIX(self):
        if not interfaces.IReactorUNIX(reactor, None):
            raise unittest.SkipTest, "This reactor does not support UNIX domain sockets"
        s = service.MultiService()
        c = compat.IOldApplication(s)
        factory = protocol.ServerFactory()
        factory.protocol = TestEcho
        TestEcho.d = defer.Deferred()
        if os.path.exists('.hello.skt'):
            os.remove('hello.skt')
        c.listenUNIX('./hello.skt', factory)

        class Foo(basic.LineReceiver):
            def connectionMade(self):
                self.transport.write('lalala\r\n')

            def lineReceived(self, line):
                self.factory.line = line
                self.transport.loseConnection()

        factory = protocol.ClientFactory()
        factory.protocol = Foo
        factory.line = None
        c.connectUNIX('./hello.skt', factory)
        s.privilegedStartService()
        s.startService()
        util.spinWhile(lambda: factory.line is None)
        util.wait(defer.maybeDeferred(s.stopService))
        self.assertEqual(factory.line, 'lalala')

        # Cleanup the reactor
        util.wait(TestEcho.d)
Exemple #3
0
 def testStoppingServer(self):
     if not interfaces.IReactorUNIX(reactor, None):
         raise unittest.SkipTest, "This reactor does not support UNIX domain sockets"
     factory = protocol.ServerFactory()
     factory.protocol = wire.Echo
     t = internet.UNIXServer('echo.skt', factory)
     t.startService()
     t.stopService()
     self.failIf(t.running)
     factory = protocol.ClientFactory()
     d = defer.Deferred()
     factory.clientConnectionFailed = lambda *args: d.callback(None)
     reactor.connectUNIX('echo.skt', factory)
     return d
 def testStoppingServer(self):
     if not interfaces.IReactorUNIX(reactor, None):
         raise unittest.SkipTest, "This reactor does not support UNIX domain sockets"
     factory = protocol.ServerFactory()
     factory.protocol = wire.Echo
     t = internet.UNIXServer('echo.skt', factory)
     t.startService()
     t.stopService()
     self.failIf(t.running)
     factory = protocol.ClientFactory()
     l = []
     factory.clientConnectionFailed = lambda *args: l.append(None)
     reactor.connectUNIX('echo.skt', factory)
     util.spinWhile(lambda: not l)
     self.assertEqual(l, [None])
Exemple #5
0
 def testUNIX(self):
     # FIXME: This test is far too dense.  It needs comments.
     #  -- spiv, 2004-11-07
     if not interfaces.IReactorUNIX(reactor, None):
         raise unittest.SkipTest, "This reactor does not support UNIX domain sockets"
     s = service.MultiService()
     s.startService()
     factory = protocol.ServerFactory()
     factory.protocol = TestEcho
     TestEcho.d = defer.Deferred()
     t = internet.UNIXServer('echo.skt', factory)
     t.setServiceParent(s)
     factory = protocol.ClientFactory()
     factory.protocol = Foo
     factory.d = defer.Deferred()
     factory.line = None
     internet.UNIXClient('echo.skt', factory).setServiceParent(s)
     factory.d.addCallback(self.assertEqual, 'lalala')
     factory.d.addCallback(lambda x: s.stopService())
     factory.d.addCallback(lambda x: TestEcho.d)
     factory.d.addCallback(self._cbTestUnix, factory, s)
     return factory.d
 def testUNIX(self):
     if not interfaces.IReactorUNIX(reactor, None):
         raise unittest.SkipTest, "This reactor does not support UNIX domain sockets"
     s = service.MultiService()
     c = compat.IOldApplication(s)
     factory = protocol.ServerFactory()
     factory.protocol = TestEcho
     TestEcho.d = defer.Deferred()
     if os.path.exists('.hello.skt'):
         os.remove('hello.skt')
     c.listenUNIX('./hello.skt', factory)
     factory = protocol.ClientFactory()
     factory.d = defer.Deferred()
     factory.protocol = Foo
     factory.line = None
     c.connectUNIX('./hello.skt', factory)
     s.privilegedStartService()
     s.startService()
     factory.d.addCallback(self.assertEqual, 'lalala')
     factory.d.addCallback(lambda x: s.stopService())
     factory.d.addCallback(lambda x: TestEcho.d)
     return factory.d
    def testUNIX(self):
        # FIXME: This test is far too dense.  It needs comments.
        #  -- spiv, 2004-11-07
        if not interfaces.IReactorUNIX(reactor, None):
            raise unittest.SkipTest, "This reactor does not support UNIX domain sockets"
        s = service.MultiService()
        s.startService()
        factory = protocol.ServerFactory()
        factory.protocol = TestEcho
        TestEcho.d = defer.Deferred()
        t = internet.UNIXServer('echo.skt', factory)
        t.setServiceParent(s)

        class Foo(basic.LineReceiver):
            def connectionMade(self):
                self.transport.write('lalala\r\n')

            def lineReceived(self, line):
                self.factory.line = line
                self.transport.loseConnection()

        factory = protocol.ClientFactory()
        factory.protocol = Foo
        factory.line = None
        internet.UNIXClient('echo.skt', factory).setServiceParent(s)
        util.spinWhile(lambda: factory.line is None)
        self.assertEqual(factory.line, 'lalala')
        util.wait(defer.maybeDeferred(s.stopService))
        util.wait(TestEcho.d)

        TestEcho.d = defer.Deferred()
        factory.line = None
        s.startService()
        util.spinWhile(lambda: factory.line is None)
        self.assertEqual(factory.line, 'lalala')

        # Cleanup the reactor
        util.wait(defer.maybeDeferred(s.stopService))
        util.wait(TestEcho.d)
 def testSimpleUNIX(self):
     # XXX - replace this test with one that does the same thing, but
     # with no web dependencies.
     if not interfaces.IReactorUNIX(reactor, None):
         raise unittest.SkipTest, "This reactor does not support UNIX domain sockets"
     if not gotMicrodom:
         raise unittest.SkipTest("Need twisted.web to run this test.")
     s = "(dp0\nS'udpConnectors'\np1\n(lp2\nsS'unixConnectors'\np3\n(lp4\nsS'twisted.internet.app.Application.persistenceVersion'\np5\nI12\nsS'name'\np6\nS'web'\np7\nsS'sslConnectors'\np8\n(lp9\nsS'sslPorts'\np10\n(lp11\nsS'tcpPorts'\np12\n(lp13\nsS'unixPorts'\np14\n(lp15\n(S'/home/moshez/.twistd-web-pb'\np16\n(itwisted.spread.pb\nBrokerFactory\np17\n(dp19\nS'objectToBroker'\np20\n(itwisted.web.distrib\nResourcePublisher\np21\n(dp22\nS'twisted.web.distrib.ResourcePublisher.persistenceVersion'\np23\nI2\nsS'site'\np24\n(itwisted.web.server\nSite\np25\n(dp26\nS'resource'\np27\n(itwisted.web.static\nFile\np28\n(dp29\nS'ignoredExts'\np30\n(lp31\nsS'defaultType'\np32\nS'text/html'\np33\nsS'registry'\np34\n(itwisted.web.static\nRegistry\np35\n(dp36\nS'twisted.web.static.Registry.persistenceVersion'\np37\nI1\nsS'twisted.python.components.Componentized.persistenceVersion'\np38\nI1\nsS'_pathCache'\np39\n(dp40\nsS'_adapterCache'\np41\n(dp42\nS'twisted.internet.interfaces.IServiceCollection'\np43\n(itwisted.internet.app\nApplication\np44\n(dp45\ng1\ng2\nsg3\ng4\nsg5\nI12\nsg6\ng7\nsg8\ng9\nsg10\ng11\nsg12\ng13\nsg14\ng15\nsS'extraPorts'\np46\n(lp47\nsS'gid'\np48\nI1053\nsS'tcpConnectors'\np49\n(lp50\nsS'extraConnectors'\np51\n(lp52\nsS'udpPorts'\np53\n(lp54\nsS'services'\np55\n(dp56\nsS'persistStyle'\np57\nS'pickle'\np58\nsS'delayeds'\np59\n(lp60\nsS'uid'\np61\nI1053\nsbssbsS'encoding'\np62\nNsS'twisted.web.static.File.persistenceVersion'\np63\nI6\nsS'path'\np64\nS'/home/moshez/public_html.twistd'\np65\nsS'type'\np66\ng33\nsS'children'\np67\n(dp68\nsS'processors'\np69\n(dp70\nS'.php3'\np71\nctwisted.web.twcgi\nPHP3Script\np72\nsS'.rpy'\np73\nctwisted.web.script\nResourceScript\np74\nsS'.php'\np75\nctwisted.web.twcgi\nPHPScript\np76\nsS'.cgi'\np77\nctwisted.web.twcgi\nCGIScript\np78\nsS'.epy'\np79\nctwisted.web.script\nPythonScript\np80\nsS'.trp'\np81\nctwisted.web.trp\nResourceUnpickler\np82\nssbsS'logPath'\np83\nNsS'sessions'\np84\n(dp85\nsbsbsS'twisted.spread.pb.BrokerFactory.persistenceVersion'\np86\nI3\nsbI5\nI438\ntp87\nasg55\ng56\nsg48\nI1053\nsg49\ng50\nsg51\ng52\nsg53\ng54\nsg46\ng47\nsg57\ng58\nsg61\nI1053\nsg59\ng60\ns."
     d = pickle.loads(s)
     a = Dummy()
     a.__dict__ = d
     appl = compat.convert(a)
     self.assertEqual(service.IProcess(appl).uid, 1053)
     self.assertEqual(service.IProcess(appl).gid, 1053)
     self.assertEqual(service.IService(appl).name, "web")
     services = list(service.IServiceCollection(appl))
     self.assertEqual(len(services), 1)
     s = services[0]
     self.assertEqual(s.parent, service.IServiceCollection(appl))
     self.assert_(s.privileged)
     self.assert_(isinstance(s, internet.UNIXServer))
     args = s.args
     self.assertEqual(args[0], '/home/moshez/.twistd-web-pb')
Exemple #9
0
    def testVolatile(self):
        if not interfaces.IReactorUNIX(reactor, None):
            raise unittest.SkipTest, "This reactor does not support UNIX domain sockets"
        factory = protocol.ServerFactory()
        factory.protocol = wire.Echo
        t = internet.UNIXServer('echo.skt', factory)
        t.startService()
        self.failIfIdentical(t._port, None)
        t1 = copy.copy(t)
        self.assertIdentical(t1._port, None)
        t.stopService()
        self.assertIdentical(t._port, None)
        self.failIf(t.running)

        factory = protocol.ClientFactory()
        factory.protocol = wire.Echo
        t = internet.UNIXClient('echo.skt', factory)
        t.startService()
        self.failIfIdentical(t._connection, None)
        t1 = copy.copy(t)
        self.assertIdentical(t1._connection, None)
        t.stopService()
        self.assertIdentical(t._connection, None)
        self.failIf(t.running)
    if _PY3:
        test_reprWithClassicProtocol.skip = (
            "Classic classes do not exist on Python 3.")

    def test_reprWithNewStyleProtocol(self):
        """
        The two string representations of the L{IListeningPort} returned by
        L{IReactorUNIXDatagram.listenUNIXDatagram} contains the name of the
        new-style protocol class being used and the filename on which the port
        is listening or indicates that the port is not listening.
        """
        class NewStyleProtocol(object):
            def makeConnection(self, transport):
                pass

            def doStop(self):
                pass

        # Sanity check
        self.assertIsInstance(NewStyleProtocol, type)

        return self._reprTest(NewStyleProtocol(),
                              "twisted.test.test_unix.NewStyleProtocol")


if not interfaces.IReactorUNIX(reactor, None):
    UnixSocketTests.skip = "This reactor does not support UNIX domain sockets"
if not interfaces.IReactorUNIXDatagram(reactor, None):
    DatagramUnixSocketTests.skip = "This reactor does not support UNIX datagram sockets"
Exemple #11
0
from twisted.python.compat import _PY3, networkString
from twisted.python.filepath import FilePath
from twisted.trial import unittest

from twisted.test.test_tcp import MyServerFactory, MyClientFactory


class FailedConnectionClientFactory(protocol.ClientFactory):
    def __init__(self, onFail):
        self.onFail = onFail

    def clientConnectionFailed(self, connector, reason):
        self.onFail.errback(reason)


@skipIf(not interfaces.IReactorUNIX(reactor, None),
        "This reactor does not support UNIX domain sockets")
class UnixSocketTests(unittest.TestCase):
    """
    Test unix sockets.
    """
    def test_peerBind(self):
        """
        The address passed to the server factory's C{buildProtocol} method and
        the address returned by the connected protocol's transport's C{getPeer}
        method match the address the client socket is bound to.
        """
        filename = self.mktemp()
        peername = self.mktemp()
        serverFactory = MyServerFactory()
        connMade = serverFactory.protocolConnectionMade = defer.Deferred()
Exemple #12
0
class InternetTests(TestCase):
    def testTCP(self):
        s = service.MultiService()
        s.startService()
        factory = protocol.ServerFactory()
        factory.protocol = TestEcho
        TestEcho.d = defer.Deferred()
        t = internet.TCPServer(0, factory)
        t.setServiceParent(s)
        num = t._port.getHost().port
        factory = protocol.ClientFactory()
        factory.d = defer.Deferred()
        factory.protocol = Foo
        factory.line = None
        internet.TCPClient("127.0.0.1", num, factory).setServiceParent(s)
        factory.d.addCallback(self.assertEqual, b"lalala")
        factory.d.addCallback(lambda x: s.stopService())
        factory.d.addCallback(lambda x: TestEcho.d)
        return factory.d

    def test_UDP(self):
        """
        Test L{internet.UDPServer} with a random port: starting the service
        should give it valid port, and stopService should free it so that we
        can start a server on the same port again.
        """
        if not interfaces.IReactorUDP(reactor, None):
            raise SkipTest("This reactor does not support UDP sockets")
        p = protocol.DatagramProtocol()
        t = internet.UDPServer(0, p)
        t.startService()
        num = t._port.getHost().port
        self.assertNotEqual(num, 0)

        def onStop(ignored):
            t = internet.UDPServer(num, p)
            t.startService()
            return t.stopService()

        return defer.maybeDeferred(t.stopService).addCallback(onStop)

    def testPrivileged(self):
        factory = protocol.ServerFactory()
        factory.protocol = TestEcho
        TestEcho.d = defer.Deferred()
        t = internet.TCPServer(0, factory)
        t.privileged = 1
        t.privilegedStartService()
        num = t._port.getHost().port
        factory = protocol.ClientFactory()
        factory.d = defer.Deferred()
        factory.protocol = Foo
        factory.line = None
        c = internet.TCPClient("127.0.0.1", num, factory)
        c.startService()
        factory.d.addCallback(self.assertEqual, b"lalala")
        factory.d.addCallback(lambda x: c.stopService())
        factory.d.addCallback(lambda x: t.stopService())
        factory.d.addCallback(lambda x: TestEcho.d)
        return factory.d

    def testConnectionGettingRefused(self):
        factory = protocol.ServerFactory()
        factory.protocol = wire.Echo
        t = internet.TCPServer(0, factory)
        t.startService()
        num = t._port.getHost().port
        t.stopService()
        d = defer.Deferred()
        factory = protocol.ClientFactory()
        factory.clientConnectionFailed = lambda *args: d.callback(None)
        c = internet.TCPClient("127.0.0.1", num, factory)
        c.startService()
        return d

    @skipIf(
        not interfaces.IReactorUNIX(reactor, None),
        "This reactor does not support UNIX domain sockets",
    )
    def testUNIX(self):
        # FIXME: This test is far too dense.  It needs comments.
        #  -- spiv, 2004-11-07
        s = service.MultiService()
        s.startService()
        factory = protocol.ServerFactory()
        factory.protocol = TestEcho
        TestEcho.d = defer.Deferred()
        t = internet.UNIXServer("echo.skt", factory)
        t.setServiceParent(s)
        factory = protocol.ClientFactory()
        factory.protocol = Foo
        factory.d = defer.Deferred()
        factory.line = None
        internet.UNIXClient("echo.skt", factory).setServiceParent(s)
        factory.d.addCallback(self.assertEqual, b"lalala")
        factory.d.addCallback(lambda x: s.stopService())
        factory.d.addCallback(lambda x: TestEcho.d)
        factory.d.addCallback(self._cbTestUnix, factory, s)
        return factory.d

    def _cbTestUnix(self, ignored, factory, s):
        TestEcho.d = defer.Deferred()
        factory.line = None
        factory.d = defer.Deferred()
        s.startService()
        factory.d.addCallback(self.assertEqual, b"lalala")
        factory.d.addCallback(lambda x: s.stopService())
        factory.d.addCallback(lambda x: TestEcho.d)
        return factory.d

    @skipIf(
        not interfaces.IReactorUNIX(reactor, None),
        "This reactor does not support UNIX domain sockets",
    )
    def testVolatile(self):
        factory = protocol.ServerFactory()
        factory.protocol = wire.Echo
        t = internet.UNIXServer("echo.skt", factory)
        t.startService()
        self.failIfIdentical(t._port, None)
        t1 = copy.copy(t)
        self.assertIsNone(t1._port)
        t.stopService()
        self.assertIsNone(t._port)
        self.assertFalse(t.running)

        factory = protocol.ClientFactory()
        factory.protocol = wire.Echo
        t = internet.UNIXClient("echo.skt", factory)
        t.startService()
        self.failIfIdentical(t._connection, None)
        t1 = copy.copy(t)
        self.assertIsNone(t1._connection)
        t.stopService()
        self.assertIsNone(t._connection)
        self.assertFalse(t.running)

    @skipIf(
        not interfaces.IReactorUNIX(reactor, None),
        "This reactor does not support UNIX domain sockets",
    )
    def testStoppingServer(self):
        factory = protocol.ServerFactory()
        factory.protocol = wire.Echo
        t = internet.UNIXServer("echo.skt", factory)
        t.startService()
        t.stopService()
        self.assertFalse(t.running)
        factory = protocol.ClientFactory()
        d = defer.Deferred()
        factory.clientConnectionFailed = lambda *args: d.callback(None)
        reactor.connectUNIX("echo.skt", factory)
        return d

    def testPickledTimer(self):
        target = TimerTarget()
        t0 = internet.TimerService(1, target.append, "hello")
        t0.startService()
        s = pickle.dumps(t0)
        t0.stopService()

        t = pickle.loads(s)
        self.assertFalse(t.running)

    def testBrokenTimer(self):
        d = defer.Deferred()
        t = internet.TimerService(1, lambda: 1 // 0)
        oldFailed = t._failed

        def _failed(why):
            oldFailed(why)
            d.callback(None)

        t._failed = _failed
        t.startService()
        d.addCallback(lambda x: t.stopService)
        d.addCallback(lambda x: self.assertEqual(
            [ZeroDivisionError],
            [
                o.value.__class__
                for o in self.flushLoggedErrors(ZeroDivisionError)
            ],
        ))
        return d

    def test_everythingThere(self):
        """
        L{twisted.application.internet} dynamically defines a set of
        L{service.Service} subclasses that in general have corresponding
        reactor.listenXXX or reactor.connectXXX calls.
        """
        trans = ["TCP", "UNIX", "SSL", "UDP", "UNIXDatagram", "Multicast"]
        for tran in trans[:]:
            if not getattr(interfaces, "IReactor" + tran)(reactor, None):
                trans.remove(tran)
        for tran in trans:
            for side in ["Server", "Client"]:
                if tran == "Multicast" and side == "Client":
                    continue
                if tran == "UDP" and side == "Client":
                    continue
                self.assertTrue(hasattr(internet, tran + side))
                method = getattr(internet, tran + side).method
                prefix = {"Server": "listen", "Client": "connect"}[side]
                self.assertTrue(
                    hasattr(reactor, prefix + method)
                    or (prefix == "connect" and method == "UDP"))
                o = getattr(internet, tran + side)()
                self.assertEqual(service.IService(o), o)

    def test_importAll(self):
        """
        L{twisted.application.internet} dynamically defines L{service.Service}
        subclasses. This test ensures that the subclasses exposed by C{__all__}
        are valid attributes of the module.
        """
        for cls in internet.__all__:
            self.assertTrue(
                hasattr(internet, cls),
                f"{cls} not importable from twisted.application.internet",
            )

    def test_reactorParametrizationInServer(self):
        """
        L{internet._AbstractServer} supports a C{reactor} keyword argument
        that can be used to parametrize the reactor used to listen for
        connections.
        """
        reactor = MemoryReactor()

        factory = object()
        t = internet.TCPServer(1234, factory, reactor=reactor)
        t.startService()
        self.assertEqual(reactor.tcpServers.pop()[:2], (1234, factory))

    def test_reactorParametrizationInClient(self):
        """
        L{internet._AbstractClient} supports a C{reactor} keyword arguments
        that can be used to parametrize the reactor used to create new client
        connections.
        """
        reactor = MemoryReactor()

        factory = protocol.ClientFactory()
        t = internet.TCPClient("127.0.0.1", 1234, factory, reactor=reactor)
        t.startService()
        self.assertEqual(reactor.tcpClients.pop()[:3],
                         ("127.0.0.1", 1234, factory))

    def test_reactorParametrizationInServerMultipleStart(self):
        """
        Like L{test_reactorParametrizationInServer}, but stop and restart the
        service and check that the given reactor is still used.
        """
        reactor = MemoryReactor()

        factory = protocol.Factory()
        t = internet.TCPServer(1234, factory, reactor=reactor)
        t.startService()
        self.assertEqual(reactor.tcpServers.pop()[:2], (1234, factory))
        t.stopService()
        t.startService()
        self.assertEqual(reactor.tcpServers.pop()[:2], (1234, factory))

    def test_reactorParametrizationInClientMultipleStart(self):
        """
        Like L{test_reactorParametrizationInClient}, but stop and restart the
        service and check that the given reactor is still used.
        """
        reactor = MemoryReactor()

        factory = protocol.ClientFactory()
        t = internet.TCPClient("127.0.0.1", 1234, factory, reactor=reactor)
        t.startService()
        self.assertEqual(reactor.tcpClients.pop()[:3],
                         ("127.0.0.1", 1234, factory))
        t.stopService()
        t.startService()
        self.assertEqual(reactor.tcpClients.pop()[:3],
                         ("127.0.0.1", 1234, factory))
class UnixSocketTests(unittest.TestCase):
    """
    Test unix sockets.
    """

    if not interfaces.IReactorUNIX(reactor, None):
        skip = "This reactor does not support UNIX domain sockets"

    def test_peerBind(self):
        """
        The address passed to the server factory's C{buildProtocol} method and
        the address returned by the connected protocol's transport's C{getPeer}
        method match the address the client socket is bound to.
        """
        filename = self.mktemp()
        peername = self.mktemp()
        serverFactory = MyServerFactory()
        connMade = serverFactory.protocolConnectionMade = defer.Deferred()
        unixPort = reactor.listenUNIX(filename, serverFactory)
        self.addCleanup(unixPort.stopListening)
        unixSocket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        self.addCleanup(unixSocket.close)
        unixSocket.bind(peername)
        unixSocket.connect(filename)

        def cbConnMade(proto):
            expected = address.UNIXAddress(peername)
            self.assertEqual(serverFactory.peerAddresses, [expected])
            self.assertEqual(proto.transport.getPeer(), expected)

        connMade.addCallback(cbConnMade)
        return connMade

    def test_dumber(self):
        """
        L{IReactorUNIX.connectUNIX} can be used to connect a client to a server
        started with L{IReactorUNIX.listenUNIX}.
        """
        filename = self.mktemp()
        serverFactory = MyServerFactory()
        serverConnMade = defer.Deferred()
        serverFactory.protocolConnectionMade = serverConnMade
        unixPort = reactor.listenUNIX(filename, serverFactory)
        self.addCleanup(unixPort.stopListening)
        clientFactory = MyClientFactory()
        clientConnMade = defer.Deferred()
        clientFactory.protocolConnectionMade = clientConnMade
        reactor.connectUNIX(filename, clientFactory)
        d = defer.gatherResults([serverConnMade, clientConnMade])

        def allConnected(args):
            serverProtocol, clientProtocol = args
            # Incidental assertion which may or may not be redundant with some
            # other test.  This probably deserves its own test method.
            self.assertEqual(clientFactory.peerAddresses,
                             [address.UNIXAddress(filename)])

            clientProtocol.transport.loseConnection()
            serverProtocol.transport.loseConnection()

        d.addCallback(allConnected)
        return d

    def test_pidFile(self):
        """
        A lockfile is created and locked when L{IReactorUNIX.listenUNIX} is
        called and released when the Deferred returned by the L{IListeningPort}
        provider's C{stopListening} method is called back.
        """
        filename = self.mktemp()
        serverFactory = MyServerFactory()
        serverConnMade = defer.Deferred()
        serverFactory.protocolConnectionMade = serverConnMade
        unixPort = reactor.listenUNIX(filename, serverFactory, wantPID=True)
        self.assertTrue(lockfile.isLocked(filename + ".lock"))

        # XXX This part would test something about the checkPID parameter, but
        # it doesn't actually.  It should be rewritten to test the several
        # different possible behaviors.  -exarkun
        clientFactory = MyClientFactory()
        clientConnMade = defer.Deferred()
        clientFactory.protocolConnectionMade = clientConnMade
        reactor.connectUNIX(filename, clientFactory, checkPID=1)

        d = defer.gatherResults([serverConnMade, clientConnMade])

        def _portStuff(args):
            serverProtocol, clientProto = args

            # Incidental assertion which may or may not be redundant with some
            # other test.  This probably deserves its own test method.
            self.assertEqual(clientFactory.peerAddresses,
                             [address.UNIXAddress(filename)])

            clientProto.transport.loseConnection()
            serverProtocol.transport.loseConnection()
            return unixPort.stopListening()

        d.addCallback(_portStuff)

        def _check(ignored):
            self.assertFalse(lockfile.isLocked(filename + ".lock"), 'locked')

        d.addCallback(_check)
        return d

    def test_socketLocking(self):
        """
        L{IReactorUNIX.listenUNIX} raises L{error.CannotListenError} if passed
        the name of a file on which a server is already listening.
        """
        filename = self.mktemp()
        serverFactory = MyServerFactory()
        unixPort = reactor.listenUNIX(filename, serverFactory, wantPID=True)

        self.assertRaises(error.CannotListenError,
                          reactor.listenUNIX,
                          filename,
                          serverFactory,
                          wantPID=True)

        def stoppedListening(ign):
            unixPort = reactor.listenUNIX(filename,
                                          serverFactory,
                                          wantPID=True)
            return unixPort.stopListening()

        return unixPort.stopListening().addCallback(stoppedListening)

    def _uncleanSocketTest(self, callback):
        self.filename = self.mktemp()
        source = networkString(
            ("from twisted.internet import protocol, reactor\n"
             "reactor.listenUNIX(%r, protocol.ServerFactory(),"
             "wantPID=True)\n") % (self.filename, ))
        env = {
            b'PYTHONPATH':
            FilePath(os.pathsep.join(sys.path)).asBytesMode().path
        }
        pyExe = FilePath(sys.executable).asBytesMode().path

        d = utils.getProcessValue(pyExe, (b"-u", b"-c", source), env=env)
        d.addCallback(callback)
        return d

    def test_uncleanServerSocketLocking(self):
        """
        If passed C{True} for the C{wantPID} parameter, a server can be started
        listening with L{IReactorUNIX.listenUNIX} when passed the name of a
        file on which a previous server which has not exited cleanly has been
        listening using the C{wantPID} option.
        """
        def ranStupidChild(ign):
            # If this next call succeeds, our lock handling is correct.
            p = reactor.listenUNIX(self.filename,
                                   MyServerFactory(),
                                   wantPID=True)
            return p.stopListening()

        return self._uncleanSocketTest(ranStupidChild)

    def test_connectToUncleanServer(self):
        """
        If passed C{True} for the C{checkPID} parameter, a client connection
        attempt made with L{IReactorUNIX.connectUNIX} fails with
        L{error.BadFileError}.
        """
        def ranStupidChild(ign):
            d = defer.Deferred()
            f = FailedConnectionClientFactory(d)
            reactor.connectUNIX(self.filename, f, checkPID=True)
            return self.assertFailure(d, error.BadFileError)

        return self._uncleanSocketTest(ranStupidChild)

    def _reprTest(self, serverFactory, factoryName):
        """
        Test the C{__str__} and C{__repr__} implementations of a UNIX port when
        used with the given factory.
        """
        filename = self.mktemp()
        unixPort = reactor.listenUNIX(filename, serverFactory)

        connectedString = "<%s on %r>" % (factoryName, filename)
        self.assertEqual(repr(unixPort), connectedString)
        self.assertEqual(str(unixPort), connectedString)

        d = defer.maybeDeferred(unixPort.stopListening)

        def stoppedListening(ign):
            unconnectedString = "<%s (not listening)>" % (factoryName, )
            self.assertEqual(repr(unixPort), unconnectedString)
            self.assertEqual(str(unixPort), unconnectedString)

        d.addCallback(stoppedListening)
        return d

    def test_reprWithNewStyleFactory(self):
        """
        The two string representations of the L{IListeningPort} returned by
        L{IReactorUNIX.listenUNIX} contains the name of the new-style factory
        class being used and the filename on which the port is listening or
        indicates that the port is not listening.
        """
        class NewStyleFactory(object):
            def doStart(self):
                pass

            def doStop(self):
                pass

        # Sanity check
        self.assertIsInstance(NewStyleFactory, type)

        return self._reprTest(NewStyleFactory(),
                              "twisted.test.test_unix.NewStyleFactory")
Exemple #14
0
class LoopbackUNIXTestCase(LoopbackTestCase):
    loopbackFunc = staticmethod(loopback.loopbackUNIX)

    if interfaces.IReactorUNIX(reactor, None) is None:
        skip = "Current reactor does not support UNIX sockets"
 def setUp(self):
     from twisted.internet import reactor, interfaces
     if interfaces.IReactorUNIX(reactor, None) is None:
         raise unittest.SkipTest(
             "Current reactor does not support UNIX sockets")