Exemple #1
0
    def test_convert_str_str_input(self):
        self.mock_object(encodeutils, 'safe_encode')
        input_value = "string_input"

        output_value = utils.convert_str(input_value)

        self.assertEqual(0, encodeutils.safe_encode.call_count)
        self.assertEqual(input_value, output_value)
Exemple #2
0
    def test_convert_str_bytes_input(self):
        self.mock_object(encodeutils, 'safe_encode')
        input_value = bytes("binary_input", "utf-8")

        output_value = utils.convert_str(input_value)

        self.assertEqual(0, encodeutils.safe_encode.call_count)
        self.assertIsInstance(output_value, str)
        self.assertEqual(str("binary_input"), output_value)
Exemple #3
0
    def test_convert_str_str_input(self):
        self.mock_object(utils.encodeutils, 'safe_encode')
        input_value = six.text_type("string_input")

        output_value = utils.convert_str(input_value)

        if six.PY2:
            utils.encodeutils.safe_encode.assert_called_once_with(input_value)
            self.assertEqual(utils.encodeutils.safe_encode.return_value,
                             output_value)
        else:
            self.assertEqual(0, utils.encodeutils.safe_encode.call_count)
            self.assertEqual(input_value, output_value)
Exemple #4
0
    def test_convert_str_bytes_input(self):
        self.mock_object(utils.encodeutils, 'safe_encode')
        if six.PY2:
            input_value = six.binary_type("binary_input")
        else:
            input_value = six.binary_type("binary_input", "utf-8")

        output_value = utils.convert_str(input_value)

        if six.PY2:
            utils.encodeutils.safe_encode.assert_called_once_with(input_value)
            self.assertEqual(utils.encodeutils.safe_encode.return_value,
                             output_value)
        else:
            self.assertEqual(0, utils.encodeutils.safe_encode.call_count)
            self.assertIsInstance(output_value, six.string_types)
            self.assertEqual(six.text_type("binary_input"), output_value)
Exemple #5
0
    def _process_stack(self, request, action, action_args,
                       content_type, body, accept):
        """Implement the processing stack."""

        # Get the implementing method
        try:
            meth, extensions = self.get_method(request, action,
                                               content_type, body)
        except (AttributeError, TypeError):
            return Fault(webob.exc.HTTPNotFound())
        except KeyError as ex:
            msg = _("There is no such action: %s") % ex.args[0]
            return Fault(webob.exc.HTTPBadRequest(explanation=msg))
        except exception.MalformedRequestBody:
            msg = _("Malformed request body")
            return Fault(webob.exc.HTTPBadRequest(explanation=msg))

        try:
            method_name = meth.__qualname__
        except AttributeError:
            method_name = 'Controller: %s Method: %s' % (
                six.text_type(self.controller), meth.__name__)

        if body:
            decoded_body = encodeutils.safe_decode(body, errors='ignore')
            msg = ("Action: '%(action)s', calling method: %(meth)s, body: "
                   "%(body)s") % {'action': action,
                                  'body': decoded_body,
                                  'meth': method_name}
            LOG.debug(strutils.mask_password(msg))
        else:
            LOG.debug("Calling method '%(meth)s'", {'meth': method_name})

        # Now, deserialize the request body...
        try:
            if content_type:
                contents = self.deserialize(meth, content_type, body)
            else:
                contents = {}
        except exception.InvalidContentType:
            msg = _("Unsupported Content-Type")
            return Fault(webob.exc.HTTPBadRequest(explanation=msg))
        except exception.MalformedRequestBody:
            msg = _("Malformed request body")
            return Fault(webob.exc.HTTPBadRequest(explanation=msg))

        # Update the action args
        action_args.update(contents)

        project_id = action_args.pop("project_id", None)
        context = request.environ.get('manila.context')
        if (context and project_id and (project_id != context.project_id)):
            msg = _("Malformed request url")
            return Fault(webob.exc.HTTPBadRequest(explanation=msg))

        # Run pre-processing extensions
        response, post = self.pre_process_extensions(extensions,
                                                     request, action_args)

        if not response:
            try:
                with ResourceExceptionHandler():
                    action_result = self.dispatch(meth, request, action_args)
            except Fault as ex:
                response = ex

        if not response:
            # No exceptions; convert action_result into a
            # ResponseObject
            resp_obj = None
            if type(action_result) is dict or action_result is None:
                resp_obj = ResponseObject(action_result)
            elif isinstance(action_result, ResponseObject):
                resp_obj = action_result
            else:
                response = action_result

            # Run post-processing extensions
            if resp_obj:
                _set_request_id_header(request, resp_obj)
                # Do a preserialize to set up the response object
                serializers = getattr(meth, 'wsgi_serializers', {})
                resp_obj._bind_method_serializers(serializers)
                if hasattr(meth, 'wsgi_code'):
                    resp_obj._default_code = meth.wsgi_code
                resp_obj.preserialize(accept, self.default_serializers)

                # Process post-processing extensions
                response = self.post_process_extensions(post, resp_obj,
                                                        request, action_args)

            if resp_obj and not response:
                response = resp_obj.serialize(request, accept,
                                              self.default_serializers)

        try:
            msg_dict = dict(url=request.url, status=response.status_int)
            msg = _("%(url)s returned with HTTP %(status)s") % msg_dict
        except AttributeError as e:
            msg_dict = dict(url=request.url, e=e)
            msg = _("%(url)s returned a fault: %(e)s") % msg_dict

        LOG.info(msg)

        if hasattr(response, 'headers'):
            for hdr, val in response.headers.items():
                val = utils.convert_str(val)
                response.headers[hdr] = val
            _set_request_id_header(request, response.headers)
            if not request.api_version_request.is_null():
                response.headers[API_VERSION_REQUEST_HEADER] = (
                    request.api_version_request.get_string())
                if request.api_version_request.experimental:
                    # NOTE(vponomaryov): Translate our boolean header
                    # to string explicitly to avoid 'TypeError' failure
                    # running manila API under Apache + mod-wsgi.
                    # It is safe to do so, because all headers are returned as
                    # strings anyway.
                    response.headers[EXPERIMENTAL_API_REQUEST_HEADER] = (
                        '%s' % request.api_version_request.experimental)
                response.headers['Vary'] = API_VERSION_REQUEST_HEADER

        return response
Exemple #6
0
    def _process_stack(self, request, action, action_args, content_type, body,
                       accept):
        """Implement the processing stack."""

        # Get the implementing method
        try:
            meth, extensions = self.get_method(request, action, content_type,
                                               body)
        except (AttributeError, TypeError):
            return Fault(webob.exc.HTTPNotFound())
        except KeyError as ex:
            msg = _("There is no such action: %s") % ex.args[0]
            return Fault(webob.exc.HTTPBadRequest(explanation=msg))
        except exception.MalformedRequestBody:
            msg = _("Malformed request body")
            return Fault(webob.exc.HTTPBadRequest(explanation=msg))

        if body:
            msg = ("Action: '%(action)s', calling method: %(meth)s, body: "
                   "%(body)s") % {
                       'action': action,
                       'body': six.text_type(body),
                       'meth': six.text_type(meth)
                   }
            LOG.debug(strutils.mask_password(msg))
        else:
            LOG.debug("Calling method '%(meth)s'",
                      {'meth': six.text_type(meth)})

        # Now, deserialize the request body...
        try:
            if content_type:
                contents = self.deserialize(meth, content_type, body)
            else:
                contents = {}
        except exception.InvalidContentType:
            msg = _("Unsupported Content-Type")
            return Fault(webob.exc.HTTPBadRequest(explanation=msg))
        except exception.MalformedRequestBody:
            msg = _("Malformed request body")
            return Fault(webob.exc.HTTPBadRequest(explanation=msg))

        # Update the action args
        action_args.update(contents)

        project_id = action_args.pop("project_id", None)
        context = request.environ.get('manila.context')
        if (context and project_id and (project_id != context.project_id)):
            msg = _("Malformed request url")
            return Fault(webob.exc.HTTPBadRequest(explanation=msg))

        # Run pre-processing extensions
        response, post = self.pre_process_extensions(extensions, request,
                                                     action_args)

        if not response:
            try:
                with ResourceExceptionHandler():
                    action_result = self.dispatch(meth, request, action_args)
            except Fault as ex:
                response = ex

        if not response:
            # No exceptions; convert action_result into a
            # ResponseObject
            resp_obj = None
            if type(action_result) is dict or action_result is None:
                resp_obj = ResponseObject(action_result)
            elif isinstance(action_result, ResponseObject):
                resp_obj = action_result
            else:
                response = action_result

            # Run post-processing extensions
            if resp_obj:
                _set_request_id_header(request, resp_obj)
                # Do a preserialize to set up the response object
                serializers = getattr(meth, 'wsgi_serializers', {})
                resp_obj._bind_method_serializers(serializers)
                if hasattr(meth, 'wsgi_code'):
                    resp_obj._default_code = meth.wsgi_code
                resp_obj.preserialize(accept, self.default_serializers)

                # Process post-processing extensions
                response = self.post_process_extensions(
                    post, resp_obj, request, action_args)

            if resp_obj and not response:
                response = resp_obj.serialize(request, accept,
                                              self.default_serializers)

        try:
            msg_dict = dict(url=request.url, status=response.status_int)
            msg = _("%(url)s returned with HTTP %(status)d") % msg_dict
        except AttributeError as e:
            msg_dict = dict(url=request.url, e=e)
            msg = _("%(url)s returned a fault: %(e)s") % msg_dict

        LOG.info(msg)

        if hasattr(response, 'headers'):
            for hdr, val in response.headers.items():
                val = utils.convert_str(val)
                response.headers[hdr] = val

            if not request.api_version_request.is_null():
                response.headers[API_VERSION_REQUEST_HEADER] = (
                    request.api_version_request.get_string())
                if request.api_version_request.experimental:
                    # NOTE(vponomaryov): Translate our boolean header
                    # to string explicitly to avoid 'TypeError' failure
                    # running manila API under Apache + mod-wsgi.
                    # It is safe to do so, because all headers are returned as
                    # strings anyway.
                    response.headers[EXPERIMENTAL_API_REQUEST_HEADER] = (
                        '%s' % request.api_version_request.experimental)
                response.headers['Vary'] = API_VERSION_REQUEST_HEADER

        return response