Python twisted.test.proto_helpers.MemoryReactor() Examples

The following are 30 code examples of twisted.test.proto_helpers.MemoryReactor(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module twisted.test.proto_helpers , or try the search function .
Example #1
Source File: test_smtp.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_cancelAfterConnectionMade(self):
        """
        When a user cancels L{twisted.mail.smtp.sendmail} after the connection
        is made, the connection is closed by
        L{twisted.internet.interfaces.ITransport.abortConnection}.
        """
        reactor = MemoryReactor()
        transport = AbortableStringTransport()
        d = smtp.sendmail("localhost", "source@address", "recipient@address",
                          b"message", reactor=reactor)
        factory = reactor.tcpClients[0][2]
        p = factory.buildProtocol(None)
        p.makeConnection(transport)
        d.cancel()
        self.assertEqual(transport.aborting, True)
        self.assertEqual(transport.disconnecting, True)
        failure = self.failureResultOf(d)
        failure.trap(defer.CancelledError) 
Example #2
Source File: test_options.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def patchInstallReactor(self):
        """
        Patch C{_options.installReactor} so we can capture usage and prevent
        actual installs.
        """
        self.installedReactors = {}

        def installReactor(name):
            if name != "fusion":
                raise NoSuchReactor()

            reactor = MemoryReactor()
            self.installedReactors[name] = reactor
            return reactor

        self.patch(_options, "installReactor", installReactor) 
Example #3
Source File: test_endpoints.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_endpointListenSuccess(self):
        """
        An endpoint can listen and returns a deferred that gets called back
        with a port instance.
        """
        mreactor = MemoryReactor()

        factory = object()

        ep, expectedArgs, expectedHost = self.createServerEndpoint(
            mreactor, factory)

        d = ep.listen(factory)

        receivedHosts = []

        def checkPortAndServer(port):
            receivedHosts.append(port.getHost())

        d.addCallback(checkPortAndServer)

        self.assertEquals(receivedHosts, [expectedHost])
        self.assertEquals(self.expectedServers(mreactor), [expectedArgs]) 
Example #4
Source File: test_proxy.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_process(self):
        """
        L{ReverseProxyRequest.process} should create a connection to its
        factory host/port, using a L{ProxyClientFactory} instantiated with the
        correct parameters, and particularly set the B{host} header to the
        factory host.
        """
        transport = StringTransportWithDisconnection()
        channel = DummyChannel(transport)
        reactor = MemoryReactor()
        request = ReverseProxyRequest(channel, False, reactor)
        request.factory = DummyFactory(u"example.com", 1234)
        request.gotLength(0)
        request.requestReceived(b'GET', b'/foo/bar', b'HTTP/1.0')

        # Check that one connection has been created, to the good host/port
        self.assertEqual(len(reactor.tcpClients), 1)
        self.assertEqual(reactor.tcpClients[0][0], u"example.com")
        self.assertEqual(reactor.tcpClients[0][1], 1234)

        # Check the factory passed to the connect, and its headers
        factory = reactor.tcpClients[0][2]
        self.assertIsInstance(factory, ProxyClientFactory)
        self.assertEqual(factory.headers, {b'host': b'example.com'}) 
Example #5
Source File: test_endpoints.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_endpointConnectNonDefaultArgs(self):
        """
        The endpoint should pass it's connectArgs parameter to the reactor's
        listen methods.
        """
        factory = object()

        mreactor = MemoryReactor()

        ep, expectedArgs, ignoredHost = self.createClientEndpoint(
            mreactor, factory,
            **self.connectArgs())

        ep.connect(factory)

        expectedClients = self.expectedClients(mreactor)

        self.assertEquals(len(expectedClients), 1)
        self.assertConnectArgs(expectedClients[0], expectedArgs) 
Example #6
Source File: test_proxy.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_getChild(self):
        """
        The L{ReverseProxyResource.getChild} method should return a resource
        instance with the same class as the originating resource, forward
        port, host, and reactor values, and update the path value with the
        value passed.
        """
        reactor = MemoryReactor()
        resource = ReverseProxyResource(u"127.0.0.1", 1234, b"/path", reactor)
        child = resource.getChild(b'foo', None)
        # The child should keep the same class
        self.assertIsInstance(child, ReverseProxyResource)
        self.assertEqual(child.path, b"/path/foo")
        self.assertEqual(child.port, 1234)
        self.assertEqual(child.host, u"127.0.0.1")
        self.assertIdentical(child.reactor, resource.reactor) 
Example #7
Source File: test_parser.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def onePrefix(self, description, expectedClass):
        """
        Test the C{haproxy} enpdoint prefix against one sub-endpoint type.

        @param description: A string endpoint description beginning with
            C{haproxy}.
        @type description: native L{str}

        @param expectedClass: the expected sub-endpoint class given the
            description.
        @type expectedClass: L{type}

        @return: the parsed endpoint
        @rtype: L{IStreamServerEndpoint}

        @raise twisted.trial.unittest.Failtest: if the parsed endpoint doesn't
            match expectations.
        """
        reactor = MemoryReactor()
        endpoint = serverFromString(reactor, description)
        self.assertIsInstance(endpoint, _WrapperServerEndpoint)
        self.assertIsInstance(endpoint._wrappedEndpoint, expectedClass)
        self.assertIs(endpoint._wrapperFactory, HAProxyWrappingFactory)
        return endpoint 
Example #8
Source File: test_endpoints.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_endpointListenNonDefaultArgs(self):
        """
        The endpoint should pass it's listenArgs parameter to the reactor's
        listen methods.
        """
        factory = object()

        mreactor = MemoryReactor()

        ep, expectedArgs, ignoredHost = self.createServerEndpoint(
            mreactor, factory,
            **self.listenArgs())

        ep.listen(factory)

        expectedServers = self.expectedServers(mreactor)

        self.assertEquals(expectedServers, [expectedArgs]) 
Example #9
Source File: test_proxy.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_process(self):
        """
        L{ReverseProxyRequest.process} should create a connection to its
        factory host/port, using a L{ProxyClientFactory} instantiated with the
        correct parameters, and particulary set the B{host} header to the
        factory host.
        """
        transport = StringTransportWithDisconnection()
        channel = DummyChannel(transport)
        reactor = MemoryReactor()
        request = ReverseProxyRequest(channel, False, reactor)
        request.factory = DummyFactory("example.com", 1234)
        request.gotLength(0)
        request.requestReceived('GET', '/foo/bar', 'HTTP/1.0')

        # Check that one connection has been created, to the good host/port
        self.assertEquals(len(reactor.tcpClients), 1)
        self.assertEquals(reactor.tcpClients[0][0], "example.com")
        self.assertEquals(reactor.tcpClients[0][1], 1234)

        # Check the factory passed to the connect, and its headers
        factory = reactor.tcpClients[0][2]
        self.assertIsInstance(factory, ProxyClientFactory)
        self.assertEquals(factory.headers, {'host': 'example.com'}) 
Example #10
Source File: test_proxy.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_processWithPort(self):
        """
        Check that L{ProxyRequest.process} correctly parse port in the incoming
        URL, and create a outgoing connection with this port.
        """
        transport = StringTransportWithDisconnection()
        channel = DummyChannel(transport)
        reactor = MemoryReactor()
        request = ProxyRequest(channel, False, reactor)
        request.gotLength(0)
        request.requestReceived('GET', 'http://example.com:1234/foo/bar',
                                'HTTP/1.0')

        # That should create one connection, with the port parsed from the URL
        self.assertEquals(len(reactor.tcpClients), 1)
        self.assertEquals(reactor.tcpClients[0][0], "example.com")
        self.assertEquals(reactor.tcpClients[0][1], 1234) 
Example #11
Source File: test_parser.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def onePrefix(self, description, expectedClass):
        """
        Test the C{haproxy} enpdoint prefix against one sub-endpoint type.

        @param description: A string endpoint description beginning with
            C{haproxy}.
        @type description: native L{str}

        @param expectedClass: the expected sub-endpoint class given the
            description.
        @type expectedClass: L{type}

        @return: the parsed endpoint
        @rtype: L{IStreamServerEndpoint}

        @raise twisted.trial.unittest.Failtest: if the parsed endpoint doesn't
            match expectations.
        """
        reactor = MemoryReactor()
        endpoint = serverFromString(reactor, description)
        self.assertIsInstance(endpoint, _WrapperServerEndpoint)
        self.assertIsInstance(endpoint._wrappedEndpoint, expectedClass)
        self.assertIs(endpoint._wrapperFactory, HAProxyWrappingFactory)
        return endpoint 
Example #12
Source File: test_proxy.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_getChild(self):
        """
        The L{ReverseProxyResource.getChild} method should return a resource
        instance with the same class as the originating resource, forward
        port, host, and reactor values, and update the path value with the
        value passed.
        """
        reactor = MemoryReactor()
        resource = ReverseProxyResource("127.0.0.1", 1234, "/path", reactor)
        child = resource.getChild('foo', None)
        # The child should keep the same class
        self.assertIsInstance(child, ReverseProxyResource)
        self.assertEquals(child.path, "/path/foo")
        self.assertEquals(child.port, 1234)
        self.assertEquals(child.host, "127.0.0.1")
        self.assertIdentical(child.reactor, resource.reactor) 
Example #13
Source File: test_smtp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_cancelAfterConnectionMade(self):
        """
        When a user cancels L{twisted.mail.smtp.sendmail} after the connection
        is made, the connection is closed by
        L{twisted.internet.interfaces.ITransport.abortConnection}.
        """
        reactor = MemoryReactor()
        transport = AbortableStringTransport()
        d = smtp.sendmail("localhost", "source@address", "recipient@address",
                          "message", reactor=reactor)
        factory = reactor.tcpClients[0][2]
        p = factory.buildProtocol(None)
        p.makeConnection(transport)
        d.cancel()
        self.assertEqual(transport.aborting, True)
        self.assertEqual(transport.disconnecting, True)
        failure = self.failureResultOf(d)
        failure.trap(defer.CancelledError) 
Example #14
Source File: test_options.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def patchInstallReactor(self):
        """
        Patch C{_options.installReactor} so we can capture usage and prevent
        actual installs.
        """
        self.installedReactors = {}

        def installReactor(name):
            if name != "fusion":
                raise NoSuchReactor()

            reactor = MemoryReactor()
            self.installedReactors[name] = reactor
            return reactor

        self.patch(_options, "installReactor", installReactor) 
Example #15
Source File: test_client.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_singleTCPQueryErrbackOnConnectionFailure(self):
        """
        The deferred returned by L{client.Resolver.queryTCP} will
        errback when the TCP connection attempt fails. The reason for
        the connection failure is passed as the argument to errback.
        """
        reactor = proto_helpers.MemoryReactor()
        resolver = client.Resolver(
            servers=[('192.0.2.100', 53)],
            reactor=reactor)

        d = resolver.queryTCP(dns.Query('example.com'))
        host, port, factory, timeout, bindAddress = reactor.tcpClients[0]

        class SentinelException(Exception):
            pass

        factory.clientConnectionFailed(
            reactor.connectors[0], failure.Failure(SentinelException()))

        self.failureResultOf(d, SentinelException) 
Example #16
Source File: test_client.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_multipleTCPQueryErrbackOnConnectionFailure(self):
        """
        All pending L{resolver.queryTCP} C{deferred}s will C{errback}
        with the same C{Failure} if the connection attempt fails.
        """
        reactor = proto_helpers.MemoryReactor()
        resolver = client.Resolver(
            servers=[('192.0.2.100', 53)],
            reactor=reactor)

        d1 = resolver.queryTCP(dns.Query('example.com'))
        d2 = resolver.queryTCP(dns.Query('example.net'))
        host, port, factory, timeout, bindAddress = reactor.tcpClients[0]

        class SentinelException(Exception):
            pass

        factory.clientConnectionFailed(
            reactor.connectors[0], failure.Failure(SentinelException()))

        f1 = self.failureResultOf(d1, SentinelException)
        f2 = self.failureResultOf(d2, SentinelException)
        self.assertIs(f1, f2) 
Example #17
Source File: test_proxy.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_process(self):
        """
        L{ReverseProxyRequest.process} should create a connection to its
        factory host/port, using a L{ProxyClientFactory} instantiated with the
        correct parameters, and particularly set the B{host} header to the
        factory host.
        """
        transport = StringTransportWithDisconnection()
        channel = DummyChannel(transport)
        reactor = MemoryReactor()
        request = ReverseProxyRequest(channel, False, reactor)
        request.factory = DummyFactory(u"example.com", 1234)
        request.gotLength(0)
        request.requestReceived(b'GET', b'/foo/bar', b'HTTP/1.0')

        # Check that one connection has been created, to the good host/port
        self.assertEqual(len(reactor.tcpClients), 1)
        self.assertEqual(reactor.tcpClients[0][0], u"example.com")
        self.assertEqual(reactor.tcpClients[0][1], 1234)

        # Check the factory passed to the connect, and its headers
        factory = reactor.tcpClients[0][2]
        self.assertIsInstance(factory, ProxyClientFactory)
        self.assertEqual(factory.headers, {b'host': b'example.com'}) 
Example #18
Source File: test_proxy.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_getChild(self):
        """
        The L{ReverseProxyResource.getChild} method should return a resource
        instance with the same class as the originating resource, forward
        port, host, and reactor values, and update the path value with the
        value passed.
        """
        reactor = MemoryReactor()
        resource = ReverseProxyResource(u"127.0.0.1", 1234, b"/path", reactor)
        child = resource.getChild(b'foo', None)
        # The child should keep the same class
        self.assertIsInstance(child, ReverseProxyResource)
        self.assertEqual(child.path, b"/path/foo")
        self.assertEqual(child.port, 1234)
        self.assertEqual(child.host, u"127.0.0.1")
        self.assertIdentical(child.reactor, resource.reactor) 
Example #19
Source File: test_application.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
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)) 
Example #20
Source File: test_client.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_singleTCPQueryErrbackOnConnectionFailure(self):
        """
        The deferred returned by L{client.Resolver.queryTCP} will
        errback when the TCP connection attempt fails. The reason for
        the connection failure is passed as the argument to errback.
        """
        reactor = proto_helpers.MemoryReactor()
        resolver = client.Resolver(
            servers=[('192.0.2.100', 53)],
            reactor=reactor)

        d = resolver.queryTCP(dns.Query('example.com'))
        host, port, factory, timeout, bindAddress = reactor.tcpClients[0]

        class SentinelException(Exception):
            pass

        factory.clientConnectionFailed(
            reactor.connectors[0], failure.Failure(SentinelException()))

        self.failureResultOf(d, SentinelException) 
Example #21
Source File: testtools.py    From flocker with Apache License 2.0 6 votes vote down vote up
def build_control_amp_service(test_case, reactor=None):
    """
    Create a new ``ControlAMPService``.

    :param TestCase test_case: The test this service is for.

    :return ControlAMPService: Not started.
    """
    if reactor is None:
        reactor = Clock()
    cluster_state = ClusterStateService(reactor)
    cluster_state.startService()
    test_case.addCleanup(cluster_state.stopService)
    persistence_service = ConfigurationPersistenceService(
        reactor, test_case.make_temporary_directory())
    persistence_service.startService()
    test_case.addCleanup(persistence_service.stopService)
    return ControlAMPService(
        reactor, cluster_state, persistence_service,
        TCP4ServerEndpoint(MemoryReactor(), 1234),
        # Easiest TLS context factory to create:
        ClientContextFactory(),
    ) 
Example #22
Source File: test_smtp.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_messageFilePassthrough(self):
        """
        L{twisted.mail.smtp.sendmail} will pass through the message untouched
        if it is a file-like object.
        """
        reactor = MemoryReactor()
        messageFile = BytesIO(b"File!")

        smtp.sendmail("localhost", "source@address", "recipient@address",
                      messageFile, reactor=reactor)
        factory = reactor.tcpClients[0][2]
        self.assertIs(factory.file, messageFile) 
Example #23
Source File: test_smtp.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_removeCurrentProtocolWhenClientConnectionFailed(self):
        """
        L{smtp.SMTPSenderFactory} removes the current protocol when the client
        connection is failed.
        """
        reactor = MemoryReactor()
        sentDeferred = defer.Deferred()
        clientFactory = smtp.SMTPSenderFactory(
            "source@address", "recipient@address",
            BytesIO(b"message"), sentDeferred)
        connector = reactor.connectTCP("localhost", 25, clientFactory)
        clientFactory.buildProtocol(None)
        clientFactory.clientConnectionFailed(connector,
                                             error.ConnectionDone("Bye."))
        self.assertEqual(clientFactory.currentProtocol, None) 
Example #24
Source File: test_runner.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_startReactorWithReactor(self):
        """
        L{Runner.startReactor} with the C{reactor} argument runs the given
        reactor.
        """
        reactor = MemoryReactor()
        runner = Runner(reactor=reactor)
        runner.startReactor()

        self.assertTrue(reactor.hasRun) 
Example #25
Source File: test_application.py    From learn_python3_spider with MIT License 5 votes vote down vote up
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)) 
Example #26
Source File: test_runner.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def _testHook(self, methodName, callerName=None):
        """
        Verify that the named hook is run with the expected arguments as
        specified by the arguments used to create the L{Runner}, when the
        specified caller is invoked.

        @param methodName: The name of the hook to verify.
        @type methodName: L{str}

        @param callerName: The name of the method that is expected to cause the
            hook to be called.
            If C{None}, use the L{Runner} method with the same name as the
            hook.
        @type callerName: L{str}
        """
        if callerName is None:
            callerName = methodName

        arguments = dict(a=object(), b=object(), c=object())
        argumentsSeen = []

        def hook(**arguments):
            argumentsSeen.append(arguments)

        runnerArguments = {
            methodName: hook,
            "{}Arguments".format(methodName): arguments.copy(),
        }
        runner = Runner(reactor=MemoryReactor(), **runnerArguments)

        hookCaller = getattr(runner, callerName)
        hookCaller()

        self.assertEqual(len(argumentsSeen), 1)
        self.assertEqual(argumentsSeen[0], arguments) 
Example #27
Source File: test_smtp.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def _honorsESMTPArguments(self, username, password):
        """
        L{twisted.mail.smtp.sendmail} creates the ESMTP factory with the ESMTP
        arguments.
        """
        reactor = MemoryReactor()
        smtp.sendmail("localhost", "source@address", "recipient@address",
                      b"message", reactor=reactor, username=username,
                      password=password, requireTransportSecurity=True,
                      requireAuthentication=True)
        factory = reactor.tcpClients[0][2]
        self.assertEqual(factory._requireTransportSecurity, True)
        self.assertEqual(factory._requireAuthentication, True)
        self.assertEqual(factory.username, b"foo")
        self.assertEqual(factory.password, b"bar") 
Example #28
Source File: test_smtp.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_messageStringMadeFile(self):
        """
        L{twisted.mail.smtp.sendmail} will turn non-file-like objects
        (eg. strings) into file-like objects before sending.
        """
        reactor = MemoryReactor()
        smtp.sendmail("localhost", "source@address", "recipient@address",
                      b"message", reactor=reactor)
        factory = reactor.tcpClients[0][2]
        messageFile = factory.file
        messageFile.seek(0)
        self.assertEqual(messageFile.read(), b"message") 
Example #29
Source File: test_smtp.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_senderDomainName(self):
        """
        L{twisted.mail.smtp.sendmail} passes through the sender domain name, if
        provided.
        """
        reactor = MemoryReactor()
        smtp.sendmail("localhost", "source@address", "recipient@address",
                      b"message", reactor=reactor, senderDomainName="foo")
        factory = reactor.tcpClients[0][2]
        self.assertEqual(factory.domain, b"foo") 
Example #30
Source File: test_runner.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_killRequestedWithPIDFileEmpty(self):
        """
        L{Runner.killIfRequested} when C{kill} is true and given a C{pidFile}
        containing no value exits with L{ExitStatus.EX_DATAERR}.
        """
        pidFile = PIDFile(DummyFilePath(b""))
        runner = Runner(reactor=MemoryReactor(), kill=True, pidFile=pidFile)
        runner.killIfRequested()

        self.assertEqual(self.exit.status, ExitStatus.EX_DATAERR)
        self.assertEqual(self.exit.message, "Invalid PID file.")