Ejemplo n.º 1
0
    def validate_include_exclude_fields(self, search):
        """ Validate the include/exclude fields param

        :param newsroom.search.SearchQuery search: The search query instance
        """
        if search.args.get('include_fields') \
                and not all(p in [c for c in list(self.allowed_include_fields)]
                            for p in search.args['include_fields'].split(',')):
            raise UnexpectedParameterError(
                'Include fields contains a non-allowed value')
        elif search.args.get('exclude_fields') \
                and not all(p in [c for c in list(self.allowed_exclude_fields)]
                            for p in search.args['exclude_fields'].split(',')):
            raise UnexpectedParameterError(
                'Exclude fields contains a non-allowed value')
Ejemplo n.º 2
0
    def _check_for_unknown_params(self,
                                  request,
                                  whitelist,
                                  allow_filtering=True):
        """Check if the request contains only allowed parameters.

        :param req: object representing the HTTP request
        :type req: `eve.utils.ParsedRequest`
        :param whitelist: iterable containing the names of allowed parameters.
        :param bool allow_filtering: whether or not the filtering parameter is
            allowed (True by default). Used for disallowing it when retrieving
            a single object.

        :raises UnexpectedParameterError:
            * if the request contains a parameter that is not whitelisted
            * if the request contains more than one value for any of the
              parameters
        """
        if not request or not getattr(request, 'args'):
            return
        request_params = request.args or MultiDict()

        if not allow_filtering:
            err_msg = ("Filtering{} is not supported when retrieving a "
                       "single object (the \"{param}\" parameter)")

            if 'q' in request_params.keys():
                desc = err_msg.format('', param='q')
                raise UnexpectedParameterError(desc=desc)

            if 'start_date' in request_params.keys():
                desc = err_msg.format(' by date range', param='start_date')
                raise UnexpectedParameterError(desc=desc)

            if 'end_date' in request_params.keys():
                desc = err_msg.format(' by date range', param='end_date')
                raise UnexpectedParameterError(desc=desc)

        for param_name in request_params.keys():
            if param_name not in whitelist:
                raise UnexpectedParameterError(
                    desc="Unexpected parameter ({})".format(param_name))

            if len(request_params.getlist(param_name)) > 1:
                desc = "Multiple values received for parameter ({})"
                raise UnexpectedParameterError(desc=desc.format(param_name))
Ejemplo n.º 3
0
    def _make_one(self, *args, **kwargs):
        """Create and return a new instance of the class under test.

        Make the test fail immediately if the class cannot be imported.
        """
        try:
            from content_api.errors import UnexpectedParameterError
        except ImportError:
            self.fail("Could not import class under test")
        else:
            return UnexpectedParameterError(*args, **kwargs)
Ejemplo n.º 4
0
    def validate_unknown_params(self, search, whitelist, allow_filtering=True):
        """ Check if the request contains only allowed parameters.

        :param newsroom.search.SearchQuery search: The search query instance
        :param whitelist: iterable containing the names of allowed parameters.
        :param bool allow_filtering: whether or not the filtering parameter is
            allowed (True by default). Used for disallowing it when retrieving
            a single object.

        :raises UnexpectedParameterError:
            * if the request contains a parameter that is not whitelisted
            * if the request contains more than one value for any of the
              parameters
        """

        arg_keys = search.args.keys()

        if not allow_filtering:
            err_msg = ("Filtering{} is not supported when retrieving a "
                       "single object (the \"{param}\" parameter)")

            if 'start_date' in arg_keys:
                desc = err_msg.format(' by date range', param='start_date')
                raise UnexpectedParameterError(desc=desc)

            if 'end_date' in arg_keys:
                desc = err_msg.format(' by date range', param='end_date')
                raise UnexpectedParameterError(desc=desc)

        for param_name in arg_keys:
            if param_name not in whitelist:
                raise UnexpectedParameterError(
                    desc="Unexpected parameter ({})".format(param_name)
                )

            if len(search.req.args.getlist(param_name)) > 1:
                desc = "Multiple values received for parameter ({})"
                raise UnexpectedParameterError(desc=desc.format(param_name))
Ejemplo n.º 5
0
    def _get_field_filter_params(self, request_params):
        """Extract the list of content fields to keep in or remove from
        the response.

        The parameter names are `include_fields` and `exclude_fields`. Both are
        simple comma-separated lists, for example::

            exclude_fields=  field_1, field_2,field_3,, ,field_4,

        NOTE: any redundant spaces, empty field values and duplicate values are
        gracefully ignored and do not cause an error.

        :param dict request_params: request parameter names and their
            corresponding values

        :return: a (include_fields, exclude_fields) tuple with each item being
            either a `set` of field names (as strings) or None if the request
            does not contain the corresponding parameter

        :raises BadParameterValueError:
            * if the request contains both parameters at the same time
            * if any of the parameters contain an unknown field name (i.e. not
                defined in the resource schema)
            * if `exclude_params` parameter contains a field name that is
                required to be present in the response according to the NINJS
                standard
        """
        include_fields = request_params.get("include_fields")
        exclude_fields = request_params.get("exclude_fields")

        # parse field filter parameters...
        strip_items = functools.partial(map, lambda s: s.strip())
        remove_empty = functools.partial(filter, None)

        if include_fields is not None:
            include_fields = include_fields.split(",")
            include_fields = set(remove_empty(strip_items(include_fields)))

        if exclude_fields is not None:
            exclude_fields = exclude_fields.split(",")
            exclude_fields = set(remove_empty(strip_items(exclude_fields)))

        # check for semantically incorrect field filter values...
        if (include_fields is not None) and (exclude_fields is not None):
            err_msg = "Cannot both include and exclude content fields " "at the same time."
            raise UnexpectedParameterError(desc=err_msg)

        if include_fields is not None:
            err_msg = "Unknown content field to include ({})."
            for field in include_fields:
                if field not in ItemsResource.schema:
                    raise BadParameterValueError(desc=err_msg.format(field))

        if exclude_fields is not None:
            if "uri" in exclude_fields:
                err_msg = "Cannot exclude a content field required by the " "NINJS format (uri)."
                raise BadParameterValueError(desc=err_msg)

            err_msg = "Unknown content field to exclude ({})."
            for field in exclude_fields:
                if field not in ItemsResource.schema:
                    raise BadParameterValueError(desc=err_msg.format(field))

        return include_fields, exclude_fields