def syncReturnError(self):
     # type: () -> Exception
     return GraphQLError("Error getting syncReturnError")
Esempio n. 2
0
    def connection_resolver(
        cls,
        resolver,
        connection,
        default_manager,
        queryset_resolver,
        max_limit,
        enforce_first_or_last,
        filterset_class,
        filters_name,
        root,
        info,
        **args,
    ):
        # Disable `enforce_first_or_last` if not querying for `edges`.
        values = [
            field.name.value
            for field in info.field_asts[0].selection_set.selections
        ]
        if "edges" not in values:
            enforce_first_or_last = False

        first = args.get("first")
        last = args.get("last")

        if enforce_first_or_last and not (first or last):
            raise GraphQLError(
                f"You must provide a `first` or `last` value to properly paginate "
                f"the `{info.field_name}` connection.")

        if max_limit:
            if first:
                assert first <= max_limit, (
                    "Requesting {} records on the `{}` connection exceeds the "
                    "`first` limit of {} records.").format(
                        first, info.field_name, max_limit)
                args["first"] = min(first, max_limit)

            if last:
                assert last <= max_limit, (
                    "Requesting {} records on the `{}` connection exceeds the "
                    "`last` limit of {} records.").format(
                        last, info.field_name, max_limit)
                args["last"] = min(last, max_limit)

        iterable = resolver(root, info, **args)

        if iterable is None:
            iterable = default_manager
        # thus the iterable gets refiltered by resolve_queryset
        # but iterable might be promise
        iterable = queryset_resolver(connection, iterable, info, args)

        on_resolve = partial(cls.resolve_connection,
                             connection,
                             args,
                             max_limit=max_limit)

        filter_input = args.get(filters_name)
        if filter_input and filterset_class:
            instance = filterset_class(data=dict(filter_input),
                                       queryset=iterable,
                                       request=info.context)
            # Make sure filter input has valid values
            if not instance.is_valid():
                raise GraphQLError(json.dumps(instance.errors.get_json_data()))
            iterable = instance.qs

        if Promise.is_thenable(iterable):
            return Promise.resolve(iterable).then(on_resolve)
        return on_resolve(iterable)
Esempio n. 3
0
 def resolver(context, *_):
     # type: (Optional[Any], *ResolveInfo) -> None
     raise GraphQLError("Failed")
Esempio n. 4
0
def _resolve_graphene_type(type_name):
    for _, _type in registry._registry.items():
        if _type._meta.name == type_name:
            return _type
    raise GraphQLError("Could not resolve the type {}".format(type_name))
Esempio n. 5
0
 def qs_with_rank(queryset: QuerySet, **_kwargs) -> QuerySet:
     if "rank" in queryset.query.annotations.keys():
         return queryset
     raise GraphQLError("Sorting by Rank is available only with searching.")
Esempio n. 6
0
 def converts_source_and_positions_to_locations():
     e = GraphQLError("msg", None, source, [6])
     assert e.nodes is None
     assert e.source is source
     assert e.positions == [6]
     assert e.locations == [(2, 5)]
Esempio n. 7
0
def _resolve_graphene_type(schema, type_name):
    type_from_schema = schema.get_type(type_name)
    if type_from_schema:
        return type_from_schema.graphene_type
    raise GraphQLError("Could not resolve the type {}".format(type_name))
Esempio n. 8
0
 def serializes_to_include_path():
     path = ["path", 3, "to", "field"]
     e = GraphQLError("msg", path=path)
     assert e.path is path
     assert repr(
         e) == "GraphQLError('msg', path=['path', 3, 'to', 'field'])"
Esempio n. 9
0
 def default_error_formatter_includes_path():
     path = ["path", 3, "to", "field"]
     e = GraphQLError("msg", path=path)
     formatted = format_error(e)
     assert formatted == e.formatted
     assert formatted == {"message": "msg", "locations": None, "path": path}
Esempio n. 10
0
    def dispatch_request(self, request):
        try:
            request_method = request.method.lower()
            data = self.parse_body(request)

            show_graphiql = request_method == "get" and self.should_display_graphiql(
                request
            )
            catch = show_graphiql

            pretty = self.pretty or show_graphiql or request.params.get("pretty")

            all_params: List[GraphQLParams]
            execution_results, all_params = run_http_query(
                self.schema,
                request_method,
                data,
                query_data=request.params,
                batch_enabled=self.batch,
                catch=catch,
                # Execute options
                run_sync=not self.enable_async,
                root_value=self.get_root_value(),
                context_value=self.get_context(request),
                middleware=self.get_middleware(),
                validation_rules=self.get_validation_rules(),
            )
            result, status_code = encode_execution_results(
                execution_results,
                is_batch=isinstance(data, list),
                format_error=self.format_error,
                encode=partial(self.encode, pretty=pretty),  # noqa
            )

            if show_graphiql:
                graphiql_data = GraphiQLData(
                    result=result,
                    query=getattr(all_params[0], "query"),
                    variables=getattr(all_params[0], "variables"),
                    operation_name=getattr(all_params[0], "operation_name"),
                    subscription_url=self.subscriptions,
                    headers=self.headers,
                )
                graphiql_config = GraphiQLConfig(
                    graphiql_version=self.graphiql_version,
                    graphiql_template=self.graphiql_template,
                    graphiql_html_title=self.graphiql_html_title,
                    jinja_env=None,
                )
                graphiql_options = GraphiQLOptions(
                    default_query=self.default_query,
                    header_editor_enabled=self.header_editor_enabled,
                    should_persist_headers=self.should_persist_headers,
                )
                return Response(
                    render_graphiql_sync(
                        data=graphiql_data,
                        config=graphiql_config,
                        options=graphiql_options,
                    ),
                    charset=self.charset,
                    content_type="text/html",
                )

            return Response(
                result,
                status=status_code,
                charset=self.charset,
                content_type="application/json",
            )

        except HttpQueryError as e:
            parsed_error = GraphQLError(e.message)
            return Response(
                self.encode(dict(errors=[self.format_error(parsed_error)])),
                status=e.status_code,
                charset=self.charset,
                headers=e.headers or {},
                content_type="application/json",
            )
Esempio n. 11
0
    def connection_resolver(
        cls,
        resolver,
        connection,
        default_manager,
        queryset_resolver,
        max_limit,
        enforce_first_or_last,
        filterset_class,
        filters_name,
        root,
        info,
        **args,
    ):
        enforce_first_or_last = cls.is_first_or_last_required(info)

        first = args.get("first")
        last = args.get("last")

        if enforce_first_or_last and not (first or last):
            raise GraphQLError(
                f"You must provide a `first` or `last` value to properly paginate "
                f"the `{info.field_name}` connection.")

        if max_limit:
            if first:
                assert first <= max_limit, (
                    "Requesting {} records on the `{}` connection exceeds the "
                    "`first` limit of {} records.").format(
                        first, info.field_name, max_limit)
                args["first"] = min(first, max_limit)

            if last:
                assert last <= max_limit, (
                    "Requesting {} records on the `{}` connection exceeds the "
                    "`last` limit of {} records.").format(
                        last, info.field_name, max_limit)
                args["last"] = min(last, max_limit)

        iterable = resolver(root, info, **args)

        if iterable is None:
            iterable = default_manager
        # thus the iterable gets refiltered by resolve_queryset
        # but iterable might be promise
        iterable = queryset_resolver(connection, iterable, info, args)

        on_resolve = partial(cls.resolve_connection,
                             connection,
                             args,
                             max_limit=max_limit)

        # for nested filters get channel from ChannelContext object
        if "channel" not in args and hasattr(root, "channel_slug"):
            args["channel"] = root.channel_slug

        iterable = cls.filter_iterable(iterable, filterset_class, filters_name,
                                       info, **args)

        if Promise.is_thenable(iterable):
            return Promise.resolve(iterable).then(on_resolve)
        return on_resolve(iterable)
 def asyncReturnError(self):
     # type: () -> Promise
     return resolved(GraphQLError("Error getting asyncReturnError"))
 def asyncEmptyReject(self):
     # type: () -> Promise
     return rejected(GraphQLError("An unknown error occurred."))
 def asyncReject(self):
     # type: () -> Promise
     return rejected(GraphQLError("Error getting asyncReject"))
Esempio n. 15
0
 def converts_single_node_to_positions_and_locations():
     e = GraphQLError("msg", field_node)  # Non-array value.
     assert e.nodes == [field_node]
     assert e.source is source
     assert e.positions == [4]
     assert e.locations == [(2, 3)]
Esempio n. 16
0
 def is_hashable():
     hash(GraphQLError("msg"))
Esempio n. 17
0
 def converts_node_with_loc_start_zero_to_positions_and_locations():
     e = GraphQLError("msg", operation_node)
     assert e.nodes == [operation_node]
     assert e.source is source
     assert e.positions == [0]
     assert e.locations == [(1, 1)]
Esempio n. 18
0
 def hashes_are_unique_per_instance():
     e1 = GraphQLError("msg")
     e2 = GraphQLError("msg")
     assert hash(e1) != hash(e2)
Esempio n. 19
0
 def serializes_to_include_message():
     e = GraphQLError("msg")
     assert str(e) == "msg"
     assert repr(e) == "GraphQLError('msg')"
Esempio n. 20
0
 def prints_an_error_without_location():
     error = GraphQLError("Error without location")
     assert print_error(error) == "Error without location"
Esempio n. 21
0
def check_currency_in_filter_data(filter_data: dict):
    currency = filter_data.get("currency")
    if not currency:
        raise GraphQLError(
            "You must provide a `currency` filter parameter for filtering by price."
        )
Esempio n. 22
0
 def prints_an_error_using_node_without_location():
     error = GraphQLError(
         "Error attached to node without location",
         parse("{ foo }", no_location=True),
     )
     assert print_error(error) == "Error attached to node without location"
Esempio n. 23
0
 def resolve_image_by_id(root: ChannelContext[models.Product], info, id):
     _type, pk = from_global_id_or_error(id, only_type="ProductMedia")
     try:
         return root.node.media.get(pk=pk)
     except models.ProductMedia.DoesNotExist:
         raise GraphQLError("Product image not found.")
Esempio n. 24
0
 def is_a_class_and_is_a_subclass_of_exception():
     assert type(GraphQLError) is type
     assert issubclass(GraphQLError, Exception)
     assert isinstance(GraphQLError("str"), Exception)
     assert isinstance(GraphQLError("str"), GraphQLError)
Esempio n. 25
0
    def execute_graphql_request(self, request: HttpRequest, data: dict):
        with opentracing.global_tracer().start_active_span(
                "graphql_query") as scope:
            span = scope.span
            span.set_tag(opentracing.tags.COMPONENT, "graphql")
            span.set_tag(
                opentracing.tags.HTTP_URL,
                request.build_absolute_uri(request.get_full_path()),
            )

            query, variables, operation_name = self.get_graphql_params(
                request, data)
            query_cost = 0

            document, error = self.parse_query(query)
            with observability.report_gql_operation() as operation:
                operation.query = document
                operation.name = operation_name
                operation.variables = variables
            if error:
                return error

            if document is not None:
                raw_query_string = document.document_string
                span.set_tag("graphql.query", raw_query_string)
                span.set_tag("graphql.query_fingerprint",
                             query_fingerprint(document))
                try:
                    query_contains_schema = self.check_if_query_contains_only_schema(
                        document)
                except GraphQLError as e:
                    return ExecutionResult(errors=[e], invalid=True)

                query_cost, cost_errors = validate_query_cost(
                    schema,
                    document,
                    variables,
                    COST_MAP,
                    settings.GRAPHQL_QUERY_MAX_COMPLEXITY,
                )
                span.set_tag("graphql.query_cost", query_cost)
                if settings.GRAPHQL_QUERY_MAX_COMPLEXITY and cost_errors:
                    result = ExecutionResult(errors=cost_errors, invalid=True)
                    return set_query_cost_on_result(result, query_cost)

            extra_options: Dict[str, Optional[Any]] = {}

            if self.executor:
                # We only include it optionally since
                # executor is not a valid argument in all backends
                extra_options["executor"] = self.executor
            try:
                with connection.execute_wrapper(tracing_wrapper):
                    response = None
                    should_use_cache_for_scheme = query_contains_schema & (
                        not settings.DEBUG)
                    if should_use_cache_for_scheme:
                        key = generate_cache_key(raw_query_string)
                        response = cache.get(key)

                    if not response:
                        response = document.execute(  # type: ignore
                            root=self.get_root_value(),
                            variables=variables,
                            operation_name=operation_name,
                            context=get_context_value(request),
                            middleware=self.middleware,
                            **extra_options,
                        )
                        if should_use_cache_for_scheme:
                            cache.set(key, response)

                    if app := getattr(request, "app", None):
                        span.set_tag("app.name", app.name)

                    return set_query_cost_on_result(response, query_cost)
            except Exception as e:
                span.set_tag(opentracing.tags.ERROR, True)
                if app := getattr(request, "app", None):
                    span.set_tag("app.name", app.name)
                # In the graphql-core version that we are using,
                # the Exception is raised for too big integers value.
                # As it's a validation error we want to raise GraphQLError instead.
                if str(e).startswith(INT_ERROR_MSG) or isinstance(
                        e, ValueError):
                    e = GraphQLError(str(e))
                return ExecutionResult(errors=[e], invalid=True)
Esempio n. 26
0
 def has_a_name_message_and_stack_trace():
     e = GraphQLError("msg")
     assert e.__class__.__name__ == "GraphQLError"
     assert e.message == "msg"
 def includes_path():
     path: List[Union[int, str]] = ["path", 3, "to", "field"]
     error = GraphQLError("msg", path=path)
     formatted = format_error(error)
     assert formatted == error.formatted
     assert formatted == {"message": "msg", "locations": None, "path": path}
Esempio n. 28
0
 def converts_nodes_to_positions_and_locations():
     e = GraphQLError("msg", [field_node])
     assert e.nodes == [field_node]
     assert e.source is source
     assert e.positions == [4]
     assert e.locations == [(2, 3)]
Esempio n. 29
0
 def resolve_image_by_id(root: models.Product, info, id):
     pk = get_database_id(info, id, ProductImage)
     try:
         return root.images.get(pk=pk)
     except models.ProductImage.DoesNotExist:
         raise GraphQLError("Product image not found.")
 def syncError(self):
     # type: () -> NoReturn
     raise GraphQLError("Error getting syncError")