示例#1
0
def build_query_params_from_request(request, organization, projects, environments):
    query_kwargs = {
        'projects': projects,
        'sort_by': request.GET.get('sort', DEFAULT_SORT_OPTION),
    }

    limit = request.GET.get('limit')
    if limit:
        try:
            query_kwargs['limit'] = int(limit)
        except ValueError:
            raise ValidationError('invalid limit')

    # TODO: proper pagination support
    cursor = request.GET.get('cursor')
    if cursor:
        query_kwargs['cursor'] = Cursor.from_string(cursor)

    query = request.GET.get('query', 'is:unresolved').strip()
    if query:
        try:
            search_filters = convert_query_values(
                parse_search_query(query),
                projects,
                request.user,
                environments,
            )
        except InvalidSearchQuery as e:
            raise ValidationError(u'Your search query could not be parsed: {}'.format(e.message))

        validate_search_filter_permissions(organization, search_filters)
        query_kwargs['search_filters'] = search_filters

    return query_kwargs
示例#2
0
def build_query_params_from_request(request, organization, projects,
                                    environments):
    query_kwargs = {
        "projects": projects,
        "sort_by": request.GET.get("sort", DEFAULT_SORT_OPTION)
    }

    limit = request.GET.get("limit")
    if limit:
        try:
            query_kwargs["limit"] = int(limit)
        except ValueError:
            raise ValidationError("invalid limit")

    # TODO: proper pagination support
    if request.GET.get("cursor"):
        try:
            query_kwargs["cursor"] = Cursor.from_string(
                request.GET.get("cursor"))
        except ValueError:
            raise ParseError(detail="Invalid cursor parameter.")
    query = request.GET.get("query", "is:unresolved").strip()
    if query:
        try:
            search_filters = convert_query_values(parse_search_query(query),
                                                  projects, request.user,
                                                  environments)
        except InvalidSearchQuery as e:
            raise ValidationError(
                u"Your search query could not be parsed: {}".format(
                    six.text_type(e)))

        validate_search_filter_permissions(organization, search_filters,
                                           request.user)
        query_kwargs["search_filters"] = search_filters

    return query_kwargs
示例#3
0
def build_query_params_from_request(request, organization, projects,
                                    environments):
    query_kwargs = {
        'projects': projects,
        'sort_by': request.GET.get('sort', DEFAULT_SORT_OPTION),
    }

    limit = request.GET.get('limit')
    if limit:
        try:
            query_kwargs['limit'] = int(limit)
        except ValueError:
            raise ValidationError('invalid limit')

    # TODO: proper pagination support
    cursor = request.GET.get('cursor')
    if cursor:
        query_kwargs['cursor'] = Cursor.from_string(cursor)

    query = request.GET.get('query', 'is:unresolved').strip()
    if query:
        try:
            search_filters = convert_query_values(
                parse_search_query(query),
                projects,
                request.user,
                environments,
            )
        except InvalidSearchQuery as e:
            raise ValidationError(
                u'Your search query could not be parsed: {}'.format(e.message))

        validate_search_filter_permissions(organization, search_filters,
                                           request.user)
        query_kwargs['search_filters'] = search_filters

    return query_kwargs
示例#4
0
 def test_is_query_inbox(self):
     assert parse_search_query("is:for_review") == [
         SearchFilter(key=SearchKey(name="for_review"),
                      operator="=",
                      value=SearchValue(True))
     ]
示例#5
0
    def test_is_query_invalid(self):
        with self.assertRaises(InvalidSearchQuery) as cm:
            parse_search_query("is:wrong")

        assert six.text_type(cm.exception).startswith(
            'Invalid value for "is" search, valid values are')
示例#6
0
 def run_test(self, query):
     validate_search_filter_permissions(self.organization,
                                        parse_search_query(query),
                                        self.user)
示例#7
0
 def run_test(self, query):
     validate_search_filter_permissions(self.organization, parse_search_query(query))
示例#8
0
    def validate(self, data):
        if not data.get("id"):
            keys = set(data.keys())
            if self.required_for_create - keys:
                raise serializers.ValidationError({
                    "fields":
                    "fields are required during creation.",
                    "conditions":
                    "conditions are required during creation.",
                })

        # Validate the query that would be created when run.
        conditions = self._get_attr(data, "conditions", "")
        fields = self._get_attr(data, "fields", []).copy()
        orderby = self._get_attr(data, "orderby", "")
        equations, fields = categorize_columns(fields)
        is_table = is_table_display_type(self.context.get("displayType"))

        if equations is not None:
            try:
                resolved_equations, _, _ = resolve_equation_list(
                    equations,
                    fields,
                    auto_add=not is_table,
                    aggregates_only=not is_table,
                )
            except (InvalidSearchQuery, ArithmeticError) as err:
                raise serializers.ValidationError(
                    {"fields": f"Invalid fields: {err}"})
        else:
            resolved_equations = []

        try:
            parse_search_query(conditions)
        except InvalidSearchQuery as err:
            # We don't know if the widget that this query belongs to is an
            # Issue widget or Discover widget. Pass the error back to the
            # Widget serializer to decide if whether or not to raise this
            # error based on the Widget's type
            data["issue_query_error"] = {
                "conditions": [f"Invalid conditions: {err}"]
            }

        try:
            # When using the eps/epm functions, they require an interval argument
            # or to provide the start/end so that the interval can be computed.
            # This uses a hard coded start/end to ensure the validation succeeds
            # since the values themselves don't matter.
            params = {
                "start": datetime.now() - timedelta(days=1),
                "end": datetime.now(),
                "project_id": [p.id for p in self.context.get("projects")],
                "organization_id": self.context.get("organization").id,
            }

            snuba_filter = get_filter(conditions, params=params)
        except InvalidSearchQuery as err:
            data["discover_query_error"] = {
                "conditions": [f"Invalid conditions: {err}"]
            }
            return data

        if orderby:
            snuba_filter.orderby = get_function_alias(orderby)
        try:
            resolve_field_list(fields,
                               snuba_filter,
                               resolved_equations=resolved_equations)
        except InvalidSearchQuery as err:
            # We don't know if the widget that this query belongs to is an
            # Issue widget or Discover widget. Pass the error back to the
            # Widget serializer to decide if whether or not to raise this
            # error based on the Widget's type
            data["discover_query_error"] = {"fields": f"Invalid fields: {err}"}

        return data
示例#9
0
    def test_is_query_invalid(self):
        with self.assertRaises(InvalidSearchQuery) as cm:
            parse_search_query('is:wrong')

        assert cm.exception.message.startswith(
            'Invalid value for "is" search, valid values are', )
示例#10
0
文件: tests.py 项目: lamphc/sentry
 def build_search_filter(self, query, projects=None, user=None):
     user = user if user is not None else self.user
     projects = projects if projects is not None else [self.project]
     return convert_query_values(parse_search_query(query), projects, user)