def test_from_response_string_format(self):
        self.printHeader("from_response")

        # Fake response representing an internal server error.
        class FakeResponse(object):
            status = 500

        fake_response = FakeResponse()

        output = exceptions.from_response(fake_response, {}).__str__()
        self.assertEquals("Error (HTTP 500)", output)

        self.printFooter("from_response")
예제 #2
0
    def request(self, *args, **kwargs):
        """
        This makes an HTTP Request to the LH server.  You should use get, post,
        delete instead.
        """
        if self.session_key and self.auth_try != 1:
            kwargs.setdefault('headers',
                              {})[self.SESSION_COOKIE_NAME] = self.session_key

        kwargs.setdefault('headers', kwargs.get('headers', {}))
        kwargs['headers']['User-Agent'] = self.USER_AGENT
        kwargs['headers']['Accept'] = 'application/json'
        if 'body' in kwargs:
            kwargs['headers']['Content-Type'] = 'application/json'
            kwargs['body'] = json.dumps(kwargs['body'])
            payload = kwargs['body']
        else:
            payload = None

        # args[0] contains the URL, args[1] contains the HTTP verb/method
        http_url = args[0]
        http_method = args[1]

        self._http_log_req(args, kwargs)
        try:
            if self.timeout:
                r = requests.request(http_method, http_url, data=payload,
                                     headers=kwargs['headers'],
                                     verify=self.secure,
                                     timeout=self.timeout)
            else:
                r = requests.request(http_method, http_url, data=payload,
                                     headers=kwargs['headers'],
                                     verify=self.secure)
        except requests.exceptions.SSLError as err:
            HTTPJSONRESTClient._logger.error("SSL certificate verification"
                                             " failed: (%s). You must have a"
                                             " valid SSL certificate or"
                                             " disable SSL verification.", err)
            raise exceptions.SSLCertFailed("SSL Certificate Verification"
                                           " Failed")
        except requests.exceptions.RequestException as err:
            raise exceptions.RequestException("Request Exception: %s" % err)
        except requests.exceptions.ConnectionError as err:
            raise exceptions.ConnectionError("Connection Error: %s" % err)
        except requests.exceptions.HTTPError as err:
            raise exceptions.HTTPError("HTTP Error: %s" % err)
        except requests.exceptions.URLRequired as err:
            raise exceptions.URLRequired("URL Required: %s" % err)
        except requests.exceptions.TooManyRedirects as err:
            raise exceptions.TooManyRedirects("Too Many Redirects: %s" % err)
        except requests.exceptions.Timeout as err:
            raise exceptions.Timeout("Timeout: %s" % err)

        resp = r.headers
        body = r.text
        if isinstance(body, bytes):
            body = body.decode('utf-8')

        # resp['status'], status['content-location'], and resp.status need to
        # be manually set as Python Requests doesnt provide them automatically
        resp['status'] = str(r.status_code)
        resp.status = r.status_code
        if 'location' not in resp:
            resp['content-location'] = r.url

        r.close()
        self._http_log_resp(resp, body)

        # Try and conver the body response to an object
        # This assumes the body of the reply is JSON
        if body:
            try:
                body = json.loads(body)
            except ValueError:
                #pprint.pprint("failed to decode json\n")
                pass
        else:
            body = None

        if resp.status >= 400:
            if body and 'message' in body:
                body['desc'] = body['message']
            raise exceptions.from_response(resp, body)

        return resp, body