Ejemplo n.º 1
0
    def request(self, url, method, **kwargs):
        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['data'] = jsonutils.dumps(kwargs['body'])
            del kwargs['body']

        self.http_log_req((
            url,
            method,
        ), kwargs)
        resp = requests.request(method, url, verify=self.verify_cert, **kwargs)
        self.http_log_resp(resp)

        if resp.text:
            try:
                body = jsonutils.loads(resp.text)
            except ValueError:
                pass
                body = None
        else:
            body = None

        if resp.status_code >= 400:
            raise exceptions.from_response(resp, method, url)

        return resp, body
Ejemplo n.º 2
0
 def assert_exception(self, ex_cls, method, url, status_code, json_data):
     ex = exceptions.from_response(
         FakeResponse(status_code=status_code,
                      headers={"Content-Type": "application/json"},
                      json_data=json_data), method, url)
     self.assertTrue(isinstance(ex, ex_cls))
     self.assertEqual(ex.message, json_data["error"]["message"])
     self.assertEqual(ex.details, json_data["error"]["details"])
     self.assertEqual(ex.method, method)
     self.assertEqual(ex.url, url)
     self.assertEqual(ex.http_status, status_code)
Ejemplo n.º 3
0
 def assert_exception(self, ex_cls, method, url, status_code, json_data):
     ex = exceptions.from_response(
         FakeResponse(status_code=status_code, headers={"Content-Type": "application/json"}, json_data=json_data),
         method,
         url,
     )
     self.assertTrue(isinstance(ex, ex_cls))
     self.assertEqual(ex.message, json_data["error"]["message"])
     self.assertEqual(ex.details, json_data["error"]["details"])
     self.assertEqual(ex.method, method)
     self.assertEqual(ex.url, url)
     self.assertEqual(ex.http_status, status_code)
Ejemplo n.º 4
0
    def test_from_response_with_text_response_format_with_no_body(self):
        method = "GET"
        url = "/fake-wsme"
        status_code = 401

        ex = exceptions.from_response(
            FakeResponse(status_code=status_code,
                         headers={"Content-Type": "text/html"}),
            method,
            url)
        self.assertTrue(isinstance(ex, exceptions.Unauthorized))
        self.assertEqual(ex.details, '')
        self.assertEqual(ex.method, method)
        self.assertEqual(ex.url, url)
        self.assertEqual(ex.http_status, status_code)
Ejemplo n.º 5
0
    def test_from_response_with_text_response_format(self):
        method = "GET"
        url = "/fake-wsme"
        status_code = 400
        text_data1 = "error_message: fake message"

        ex = exceptions.from_response(
            FakeResponse(status_code=status_code,
                         headers={"Content-Type": "text/html"},
                         text=text_data1),
            method,
            url)
        self.assertTrue(isinstance(ex, exceptions.BadRequest))
        self.assertEqual(ex.details, text_data1)
        self.assertEqual(ex.method, method)
        self.assertEqual(ex.url, url)
        self.assertEqual(ex.http_status, status_code)
Ejemplo n.º 6
0
 def assert_exception(self, ex_cls, method, url, status_code, json_data,
                      error_msg=None, error_details=None,
                      check_description=True):
     ex = exceptions.from_response(
         FakeResponse(status_code=status_code,
                      headers={"Content-Type": "application/json"},
                      json_data=json_data),
         method,
         url)
     self.assertTrue(isinstance(ex, ex_cls))
     if check_description:
         expected_msg = error_msg or json_data["error"]["message"]
         expected_details = error_details or json_data["error"]["details"]
         self.assertEqual(ex.message, expected_msg)
         self.assertEqual(ex.details, expected_details)
     self.assertEqual(ex.method, method)
     self.assertEqual(ex.url, url)
     self.assertEqual(ex.http_status, status_code)
Ejemplo n.º 7
0
    def request(self, method, url, **kwargs):
        """Send an http request with the specified characteristics.

        Wrapper around `requests.Session.request` to handle tasks such as
        setting headers, JSON encoding/decoding, and error handling.

        :param method: method of HTTP request
        :param url: URL of HTTP request
        :param kwargs: any other parameter that can be passed to
             requests.Session.request (such as `headers`) or `json`
             that will be encoded as JSON and used as `data` argument
        """
        kwargs.setdefault("headers", {})
        kwargs["headers"]["User-Agent"] = self.user_agent
        if self.original_ip:
            kwargs["headers"]["Forwarded"] = "for=%s;by=%s" % (
                self.original_ip, self.user_agent)
        if self.timeout is not None:
            kwargs.setdefault("timeout", self.timeout)
        kwargs.setdefault("verify", self.verify)
        if self.cert is not None:
            kwargs.setdefault("cert", self.cert)
        self.serialize(kwargs)

        self._http_log_req(method, url, kwargs)
        if self.timings:
            start_time = time.time()
        resp = self.http.request(method, url, **kwargs)
        if self.timings:
            self.times.append(("%s %s" % (method, url),
                               start_time, time.time()))
        self._http_log_resp(resp)

        self.last_request_id = resp.headers.get('x-openstack-request-id')

        if resp.status_code >= 400:
            _logger.debug(
                "Request returned failure status: %s",
                resp.status_code)
            raise exceptions.from_response(resp, method, url)

        return resp
Ejemplo n.º 8
0
    def _extract_service_catalog(self, url, resp, body, extract_token=True):
        """See what the auth service told us and process the response.

        We may get redirected to another site, fail or actually get
        back a service catalog with a token and our endpoints.
        """
        method = None
        if hasattr(resp, 'request') and hasattr(resp.request, 'method'):
            method = resp.request.method
        if resp.status_code == 200:  # content must always present
            try:
                self.auth_url = url
                self.service_catalog = service_catalog.ServiceCatalog(body)

                if extract_token:
                    self.auth_token = self.service_catalog.get_token()
                    self.tenant_id = self.service_catalog.get_tenant_id()

                management_url = self.service_catalog.url_for(
                    attr='region',
                    filter_value=self.region_name,
                    endpoint_type=self.endpoint_type,
                    service_type=self.service_type,
                    service_name=self.service_name,
                    share_service_name=self.share_service_name)
                self.management_url = management_url.rstrip('/')
                return None
            except exceptions.AmbiguousEndpoints:
                print("Found more than one valid endpoint. Use a more "
                      "restrictive filter")
                raise
            except KeyError:
                raise exceptions.AuthorizationFailure()
            except exceptions.EndpointNotFound:
                print("Could not find any suitable endpoint. Correct region?")
                raise

        elif resp.status_code == 305:
            return resp['location']
        else:
            raise exceptions.from_response(resp, method, url)
Ejemplo n.º 9
0
 def assert_exception(self,
                      ex_cls,
                      method,
                      url,
                      status_code,
                      json_data,
                      error_msg=None,
                      error_details=None,
                      check_description=True):
     ex = exceptions.from_response(
         FakeResponse(status_code=status_code,
                      headers={"Content-Type": "application/json"},
                      json_data=json_data), method, url)
     self.assertTrue(isinstance(ex, ex_cls))
     if check_description:
         expected_msg = error_msg or json_data["error"]["message"]
         expected_details = error_details or json_data["error"]["details"]
         self.assertEqual(ex.message, expected_msg)
         self.assertEqual(ex.details, expected_details)
     self.assertEqual(ex.method, method)
     self.assertEqual(ex.url, url)
     self.assertEqual(ex.http_status, status_code)
Ejemplo n.º 10
0
    def _v1_auth(self, url):
        if self.proxy_token:
            raise exceptions.NoTokenLookupException()

        headers = {'X-Auth-User': self.user, 'X-Auth-Key': self.password}
        if self.projectid:
            headers['X-Auth-Project-Id'] = self.projectid

        method = 'GET'
        resp, body = self.request(url, method, headers=headers)
        if resp.status_code in (200, 204):  # in some cases we get No Content
            try:
                mgmt_header = 'x-server-management-url'
                self.management_url = resp.headers[mgmt_header].rstrip('/')
                self.auth_token = resp.headers['x-auth-token']
                self.auth_url = url
            except (KeyError, TypeError):
                raise exceptions.AuthorizationFailure()
        elif resp.status_code == 305:
            return resp.headers['location']
        else:
            raise exceptions.from_response(resp, method, url)