示例#1
0
 def test_send(self):
     req = xmlrpc2scgi.SCGIRequest(MockedTransport("foo"))
     resp = req.send("bar")
     bad = "Bad response %r" % resp
     self.failUnless(resp.startswith("<?xml "), bad)
     self.failUnless("bar" in resp, bad)
     self.failIf(req.latency == 0, "Latency cannot be zero")
示例#2
0
def test_scgi_send():
    req = xmlrpc2scgi.SCGIRequest(MockedTransport(b"foo"))
    resp = req.send(b"bar")
    badmsg = "Bad response %r" % resp

    assert resp.startswith(b"<?xml "), badmsg
    assert b"bar" in resp, badmsg
    assert req.latency != 0, "Latency cannot be zero"
示例#3
0
 def test_init(self):
     r1 = xmlrpc2scgi.SCGIRequest("example.com:5000")
     r2 = xmlrpc2scgi.SCGIRequest(r1.transport)
     self.failUnless(r1.transport is r2.transport)
示例#4
0
    def __call__(self, *args, **kwargs):
        """ Execute the method call.

            `raw_xml=True` returns the unparsed XML-RPC response.
            `flatten=True` removes one nesting level in a result list (useful for multicalls).
        """
        self._proxy._requests += 1
        start = time.time()
        raw_xml = kwargs.get("raw_xml", False)
        flatten = kwargs.get("flatten", False)
        fail_silently = kwargs.get("fail_silently", False)

        try:
            # Map multicall arguments
            if not self._proxy._use_deprecated:
                if self._method_name.endswith(
                        ".multicall") or self._method_name.endswith(
                            ".multicall.filtered"):
                    if self._method_name in ("d.multicall",
                                             "d.multicall.filtered"):
                        args = (0, ) + args
                    if config.debug:
                        self._proxy.LOG.debug("BEFORE MAPPING: %r" % (args, ))
                    if self._method_name == "system.multicall":
                        for call in args[0]:
                            call["methodName"] = self._proxy._map_call(
                                call["methodName"])
                    else:
                        args = args[0:2] + tuple(
                            self._proxy._map_call(i) for i in args[2:])
                    if config.debug:
                        self._proxy.LOG.debug("AFTER MAPPING: %r" % (args, ))
                elif self._method_name in self.NEEDS_FAKE_TARGET:
                    args = (0, ) + args

            # Prepare request
            xmlreq = xmlrpclib.dumps(args,
                                     self._proxy._map_call(self._method_name))
            ##xmlreq = xmlreq.replace('\n', '')
            self._outbound = len(xmlreq)
            self._proxy._outbound += self._outbound
            self._proxy._outbound_max = max(self._proxy._outbound_max,
                                            self._outbound)

            if config.debug:
                self._proxy.LOG.debug("XMLRPC raw request: %r" % xmlreq)

            # Send it
            scgi_req = xmlrpc2scgi.SCGIRequest(self._proxy._transport)
            xmlresp = scgi_req.send(xmlreq)
            self._inbound = len(xmlresp)
            self._proxy._inbound += self._inbound
            self._proxy._inbound_max = max(self._proxy._inbound_max,
                                           self._inbound)
            self._net_latency = scgi_req.latency
            self._proxy._net_latency += self._net_latency

            # Return raw XML response?
            if raw_xml:
                return xmlresp

            # This fixes a bug with the Python xmlrpclib module
            # (has no handler for <i8> in some versions)
            xmlresp = xmlresp.replace("<i8>", "<i4>").replace("</i8>", "</i4>")

            try:
                # Deserialize data
                result = xmlrpclib.loads(xmlresp)[0][0]
            except (KeyboardInterrupt, SystemExit):
                # Don't catch these
                raise
            except:
                exc_type, exc = sys.exc_info()[:2]
                if exc_type is xmlrpclib.Fault and exc.faultCode == -501 and exc.faultString == 'Could not find info-hash.':
                    raise HashNotFound("Unknown hash for {}({}) @ {}",
                                       self._method_name,
                                       args[0] if args else '',
                                       self._proxy._url)

                if not fail_silently:
                    # Dump the bad packet, then re-raise
                    filename = "/tmp/xmlrpc2scgi-%s.xml" % os.getuid()
                    handle = open(filename, "w")
                    try:
                        handle.write("REQUEST\n")
                        handle.write(xmlreq)
                        handle.write("\nRESPONSE\n")
                        handle.write(xmlresp)
                        print >> sys.stderr, "INFO: Bad data packets written to %r" % filename
                    finally:
                        handle.close()
                raise
            else:
                try:
                    return sum(result, []) if flatten else result
                except TypeError:
                    if result and isinstance(result, list) and isinstance(
                            result[0], dict) and 'faultCode' in result[0]:
                        raise error.LoggableError(
                            "XMLRPC error in multicall: " + repr(result[0]))
                    else:
                        raise
        finally:
            # Calculate latency
            self._latency = time.time() - start
            self._proxy._latency += self._latency

            if config.debug:
                self._proxy.LOG.debug(
                    "%s(%s) took %.3f secs" % (self._method_name, ", ".join(
                        repr(i) for i in args), self._latency))
示例#5
0
def test_scgi_request_init():
    req1 = xmlrpc2scgi.SCGIRequest("example.com:5000")
    req2 = xmlrpc2scgi.SCGIRequest(req1.transport)

    assert req1.transport is req2.transport