Exemplo n.º 1
0
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(),
    )
Exemplo n.º 2
0
        def installReactor(name):
            if name != "fusion":
                raise NoSuchReactor()

            reactor = MemoryReactor()
            self.installedReactors[name] = reactor
            return reactor
Exemplo n.º 3
0
    def test_getLogFiles(self):
        """
        The reactor returned by L{loggedReactor} has a C{getLogFiles} method
        which returns a L{logstate} instance containing the active and
        completed log files tracked by the logging wrapper.
        """
        wrapped = ClientFactory()
        wrapped.protocol = Discard
        reactor = MemoryReactor()
        logged = loggedReactor(reactor)
        logged.connectTCP('127.0.0.1', 1234, wrapped)
        factory = reactor.tcpClients[0][2]

        finished = factory.buildProtocol(None)
        finished.makeConnection(StringTransport())
        finished.dataReceived('finished')
        finished.connectionLost(None)

        active = factory.buildProtocol(None)
        active.makeConnection(StringTransport())
        active.dataReceived('active')

        logs = logged.getLogFiles()
        self.assertEqual(1, len(logs.finished))
        self.assertIn('finished', logs.finished[0].getvalue())
        self.assertEqual(1, len(logs.active))
        self.assertIn('active', logs.active[0].getvalue())
Exemplo n.º 4
0
    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)
Exemplo n.º 5
0
 def test_returns_service(self):
     """
     ``create_api_service`` returns an object providing ``IService``.
     """
     reactor = MemoryReactor()
     endpoint = TCP4ServerEndpoint(reactor, 6789)
     verifyObject(IService, create_api_service(None, None, endpoint))
Exemplo n.º 6
0
    def _testProcess(self, uri, expectedURI, method="GET", data=""):
        """
        Build a request pointing at C{uri}, and check that a proxied request
        is created, pointing a C{expectedURI}.
        """
        transport = StringTransportWithDisconnection()
        channel = DummyChannel(transport)
        reactor = MemoryReactor()
        request = ProxyRequest(channel, False, reactor)
        request.gotLength(len(data))
        request.handleContentChunk(data)
        request.requestReceived(method, 'http://example.com%s' % (uri,),
                                'HTTP/1.0')

        self.assertEquals(len(reactor.tcpClients), 1)
        self.assertEquals(reactor.tcpClients[0][0], "example.com")
        self.assertEquals(reactor.tcpClients[0][1], 80)

        factory = reactor.tcpClients[0][2]
        self.assertIsInstance(factory, ProxyClientFactory)
        self.assertEquals(factory.command, method)
        self.assertEquals(factory.version, 'HTTP/1.0')
        self.assertEquals(factory.headers, {'host': 'example.com'})
        self.assertEquals(factory.data, data)
        self.assertEquals(factory.rest, expectedURI)
        self.assertEquals(factory.father, request)
Exemplo n.º 7
0
    def test_missing_ca_certificate(self):
        """
        If no CA certificate is found in the service account directory,
        ``authenticate_with_serviceaccount`` raises ``ValueError``.
        """
        t = FilePath(self.useFixture(TempDir()).join(b""))
        serviceaccount = t.child(b"serviceaccount")
        serviceaccount.makedirs()

        serviceaccount.child(b"ca.crt").setContent(b"not a cert pem")
        serviceaccount.child(b"token").setContent(b"token")

        self.patch(
            os,
            "environ",
            {
                b"KUBERNETES_SERVICE_HOST": b"example.invalid.",
                b"KUBERNETES_SERVICE_PORT": b"443",
            },
        )

        self.assertThat(
            lambda: authenticate_with_serviceaccount(
                MemoryReactor(),
                path=serviceaccount.path,
            ),
            raises(ValueError("No certificate authority certificate found.")),
        )
Exemplo n.º 8
0
    def _testRender(self, uri, expectedURI):
        """
        Check that a request pointing at C{uri} produce a new proxy connection,
        with the path of this request pointing at C{expectedURI}.
        """
        root = Resource()
        reactor = MemoryReactor()
        resource = ReverseProxyResource("127.0.0.1", 1234, "/path", reactor)
        root.putChild('index', resource)
        site = Site(root)

        transport = StringTransportWithDisconnection()
        channel = site.buildProtocol(None)
        channel.makeConnection(transport)
        # Clear the timeout if the tests failed
        self.addCleanup(channel.connectionLost, None)

        channel.dataReceived("GET %s HTTP/1.1\r\nAccept: text/html\r\n\r\n" %
                             (uri,))

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

        # Check the factory passed to the connect, and its given path
        factory = reactor.tcpClients[0][2]
        self.assertIsInstance(factory, ProxyClientFactory)
        self.assertEquals(factory.rest, expectedURI)
        self.assertEquals(factory.headers["host"], "127.0.0.1:1234")
Exemplo n.º 9
0
    def test_connectTCP(self):
        """
        Called on the object returned by L{loggedReactor}, C{connectTCP} calls
        the wrapped reactor's C{connectTCP} method with the original factory
        wrapped in a L{_TrafficLoggingFactory}.
        """
        class RecordDataProtocol(Protocol):
            def dataReceived(self, data):
                self.data = data
        proto = RecordDataProtocol()
        factory = ClientFactory()
        factory.protocol = lambda: proto
        reactor = MemoryReactor()
        logged = loggedReactor(reactor)
        logged.connectTCP('192.168.1.2', 1234, factory, 21, '127.0.0.2')
        [(host, port, factory, timeout, bindAddress)] = reactor.tcpClients
        self.assertEqual('192.168.1.2', host)
        self.assertEqual(1234, port)
        self.assertIsInstance(factory, _TrafficLoggingFactory)
        self.assertEqual(21, timeout)
        self.assertEqual('127.0.0.2', bindAddress)

        # Verify that the factory and protocol specified are really being used
        protocol = factory.buildProtocol(None)
        protocol.makeConnection(None)
        protocol.dataReceived("foo")
        self.assertEqual(proto.data, "foo")
Exemplo n.º 10
0
 def test_interface(self):
     """
     The endpoint provides L{interfaces.IStreamClientEndpoint}
     """
     clientFactory = object()
     ep, ignoredArgs, address = self.createClientEndpoint(
         MemoryReactor(), clientFactory)
     self.assertTrue(verifyObject(interfaces.IStreamClientEndpoint, ep))
Exemplo n.º 11
0
 def setUp(self):
     self.patch(client, 'theResolver', FakeResolver())
     self.reactor = MemoryReactor()
     self.factory = DummyFactory()
     self.connector = srvconnect.SRVConnector(self.reactor, 'xmpp-server',
                                              'example.org', self.factory)
     self.randIntArgs = []
     self.randIntResults = []
Exemplo n.º 12
0
 def __init__(self, rootResource):
     """
     :param rootResource: The twisted IResource at the root of the resource
         tree.
     """
     self._memoryReactor = MemoryReactor()
     self._realAgent = Agent(reactor=self._memoryReactor)
     self._rootResource = rootResource
Exemplo n.º 13
0
 def test_interface(self):
     """
     The endpoint provides L{interfaces.IStreamServerEndpoint}.
     """
     factory = object()
     ep, ignoredArgs, ignoredDest = self.createServerEndpoint(
         MemoryReactor(), factory)
     self.assertTrue(verifyObject(interfaces.IStreamServerEndpoint, ep))
Exemplo n.º 14
0
 def test_stringDescription(self):
     """
     L{serverFromString} returns a L{StandardIOEndpoint} instance with a 'stdio'
     endpoint string description.
     """
     ep = endpoints.serverFromString(MemoryReactor(), "stdio:")
     self.assertIsInstance(ep, endpoints.StandardIOEndpoint)
     self.assertIsInstance(ep._reactor, MemoryReactor)
Exemplo n.º 15
0
 def test_list_logging(self, logger):
     """
     ``_NetworkClient.list`` logs an Eliot event describing its given type.
     """
     client = network_kubernetes(
         base_url=URL.fromText(u"http://127.0.0.1/"),
         agent=Agent(MemoryReactor()),
     ).client()
     client.list(v1.Pod)
Exemplo n.º 16
0
    def test_startReactorWithReactor(self):
        """
        L{Runner.startReactor} with L{RunnerOptions.reactor} runs that reactor.
        """
        reactor = MemoryReactor()
        runner = Runner({RunnerOptions.reactor: reactor})
        runner.startReactor()

        self.assertTrue(reactor.hasRun)
Exemplo n.º 17
0
 def test_stringDescription_SAM(self):
     from twisted.internet.endpoints import serverFromString
     with mock.patch('txi2p.sam.endpoints.getSession', fakeSession):
         ep = serverFromString(
             MemoryReactor(), "i2p:/tmp/testkeys.foo:81:api=SAM:options=inbound.length\:5,outbound.length\:5:sigType=foobar")
     self.assertIsInstance(ep, SAMI2PStreamServerEndpoint)
     s = ep._sessionDeferred
     self.assertEqual(s.kwargs['options'], {'inbound.length': '5', 'outbound.length': '5'})
     self.assertEqual(s.kwargs['sigType'], 'foobar')
Exemplo n.º 18
0
 def test_memoryReactorProvides(self):
     """
     L{MemoryReactor} provides all of the attributes described by the
     interfaces it advertises.
     """
     memoryReactor = MemoryReactor()
     verifyObject(IReactorTCP, memoryReactor)
     verifyObject(IReactorSSL, memoryReactor)
     verifyObject(IReactorUNIX, memoryReactor)
Exemplo n.º 19
0
    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)
Exemplo n.º 20
0
 def test_listen_tcp_full_range(self):
     reactor = MemoryReactor()
     result = listen_tcp(self.portrange,
                         self.host,
                         Factory,
                         reactor=reactor)
     assert self.portrange[0] <= result.getHost().port <= self.portrange[1]
     assert len(reactor.tcpServers) == 1
     assert self.portrange[0] <= reactor.tcpServers[0][0] <= self.portrange[
         1]
Exemplo n.º 21
0
    def test_killNotRequested(self):
        """
        L{Runner.killIfRequested} when C{kill} is false doesn't exit and
        doesn't indiscriminately murder anyone.
        """
        runner = Runner(reactor=MemoryReactor())
        runner.killIfRequested()

        self.assertEqual(self.kill.calls, [])
        self.assertFalse(self.exit.exited)
Exemplo n.º 22
0
 def test_stringDescription_BOB(self):
     from twisted.internet.endpoints import clientFromString
     ep = clientFromString(
         MemoryReactor(), "i2p:stats.i2p:api=BOB:tunnelNick=spam:inport=12345:options=inbound.length\:5,outbound.length\:5")
     self.assertIsInstance(ep, BOBI2PClientEndpoint)
     self.assertIsInstance(ep._reactor, MemoryReactor)
     self.assertEqual(ep._dest,"stats.i2p")
     self.assertEqual(ep._tunnelNick,"spam")
     self.assertEqual(ep._inport,12345)
     self.assertEqual(ep._options, {'inbound.length': '5', 'outbound.length': '5'})
Exemplo n.º 23
0
 def test_stringDescription_BOB(self):
     from twisted.internet.endpoints import serverFromString
     ep = serverFromString(
         MemoryReactor(), "i2p:/tmp/testkeys.foo:api=BOB:tunnelNick=spam:outport=23456:options=inbound.length\:5,outbound.length\:5")
     self.assertIsInstance(ep, BOBI2PServerEndpoint)
     self.assertIsInstance(ep._reactor, MemoryReactor)
     self.assertEqual(ep._keyfile, "/tmp/testkeys.foo")
     self.assertEqual(ep._tunnelNick, "spam")
     self.assertEqual(ep._outport, 23456)
     self.assertEqual(ep._options, {'inbound.length': '5', 'outbound.length': '5'})
Exemplo n.º 24
0
 def test_twistReactorHasNoExitSignalAttr(self):
     """
     _exitWithSignal is not called if the runner's reactor does not
     implement L{twisted.internet.interfaces._ISupportsExitSignalCapturing}
     """
     reactor = MemoryReactor()
     options = TwistOptions()
     options["reactor"] = reactor
     options["fileLogObserverFactory"] = jsonFileLogObserver
     Twist.run(options)
     self.assertFalse(self.exitWithSignalCalled)
Exemplo n.º 25
0
 def test_sslTimeout(self):
     """
     For I{HTTPS} URIs, L{xmlrpc.Proxy.callRemote} passes the value it
     received for the C{connectTimeout} parameter as the C{timeout} argument
     to the underlying connectSSL call.
     """
     reactor = MemoryReactor()
     proxy = xmlrpc.Proxy(b"https://127.0.0.1:69", connectTimeout=3.0,
                          reactor=reactor)
     proxy.callRemote("someMethod")
     self.assertEqual(reactor.sslClients[0][4], 3.0)
Exemplo n.º 26
0
    def test_killRequestedWithPIDFileNotAnInt(self):
        """
        L{Runner.killIfRequested} when C{kill} is true and given a C{pidFile}
        containing a non-integer value exits with L{ExitStatus.EX_DATAERR}.
        """
        pidFile = PIDFile(DummyFilePath(b"** totally not a number, dude **"))
        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.")
Exemplo n.º 27
0
 def test_tcpTimeout(self):
     """
     For I{HTTP} URIs, L{xmlrpc.Proxy.callRemote} passes the value it
     received for the C{connectTimeout} parameter as the C{timeout} argument
     to the underlying connectTCP call.
     """
     reactor = MemoryReactor()
     proxy = xmlrpc.Proxy(b"http://68.183.227.19:69", connectTimeout=2.0,
                          reactor=reactor)
     proxy.callRemote("someMethod")
     self.assertEqual(reactor.tcpClients[0][3], 2.0)
Exemplo n.º 28
0
 def __init__(self, rootResource):
     """
     :param rootResource: The Twisted `IResource` at the root of the
         resource tree.
     """
     self._memoryReactor = MemoryReactor()
     self._realAgent = Agent.usingEndpointFactory(
         reactor=self._memoryReactor,
         endpointFactory=_EndpointFactory(self._memoryReactor))
     self._rootResource = rootResource
     self._pumps = set()
Exemplo n.º 29
0
    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.")
Exemplo n.º 30
0
 def __init__(self, testCase, rootResource):
     """
     :param testCase: A trial synchronous test case to perform assertions
         with.
     :param rootResource: The twisted IResource at the root of the resource
         tree.
     """
     self._memoryReactor = MemoryReactor()
     self._realAgent = Agent(reactor=self._memoryReactor)
     self._testCase = testCase
     self._rootResource = rootResource