Ejemplo n.º 1
0
    def dispatch_request(self):
        try:
            request_method = request.method.lower()
            data = self.parse_body()

            show_graphiql = request_method == 'get' and self.should_display_graphiql()
            catch = show_graphiql

            pretty = self.pretty or show_graphiql or request.args.get('pretty')

            execution_results, all_params = run_http_query(
                self.schema,
                request_method,
                data,
                query_data=request.args,
                batch_enabled=self.batch,
                catch=catch,

                # Execute options
                root_value=self.get_root_value(),
                context_value=self.get_context(),
                middleware=self.get_middleware(),
                executor=self.get_executor(),
            )
            result, status_code = encode_execution_results(
                execution_results,
                is_batch=isinstance(data, list),
                format_error=self.format_error,
                encode=partial(self.encode, pretty=pretty)
            )

            if show_graphiql:
                return self.render_graphiql(
                    params=all_params[0],
                    result=result
                )

            return Response(
                result,
                status=status_code,
                content_type='application/json'
            )

        except HttpQueryError as e:
            return Response(
                self.encode({
                    'errors': [self.format_error(e)]
                }),
                status=e.status_code,
                headers=e.headers,
                content_type='application/json'
            )
Ejemplo n.º 2
0
    def dispatch_request(self):
        try:
            request_method = request.method.lower()
            data = self.parse_body()

            show_graphiql = request_method == 'get' and self.should_display_graphiql(
            )
            catch = show_graphiql

            pretty = self.pretty or show_graphiql or request.args.get('pretty')

            extra_options = {}
            executor = self.get_executor()
            if executor:
                # We only include it optionally since
                # executor is not a valid argument in all backends
                extra_options['executor'] = executor

            execution_results, all_params = run_http_query(
                self.schema,
                request_method,
                data,
                query_data=request.args,
                batch_enabled=self.batch,
                catch=catch,
                backend=self.get_backend(),

                # Execute options
                root=self.get_root_value(),
                context=self.get_context(),
                middleware=self.get_middleware(),
                **extra_options)
            result, status_code = encode_execution_results(
                execution_results,
                is_batch=isinstance(data, list),
                format_error=self.format_error,
                encode=partial(self.encode, pretty=pretty))

            if show_graphiql:
                return self.render_graphiql(params=all_params[0],
                                            result=result)

            return Response(result,
                            status=status_code,
                            content_type='application/json')

        except HttpQueryError as e:
            return Response(self.encode({'errors': [self.format_error(e)]}),
                            status=e.status_code,
                            headers=e.headers,
                            content_type='application/json')
Ejemplo n.º 3
0
def test_handles_syntax_errors_caught_by_graphql():
    results, params = run_http_query(schema, "get", dict(query="syntaxerror"))

    assert as_dicts(results) == [{
        "errors": [{
            "locations": [{
                "line": 1,
                "column": 1
            }],
            "message":
            "Syntax Error GraphQL (1:1)"
            ' Unexpected Name "syntaxerror"\n\n1: syntaxerror\n   ^\n',
        }]
    }]
Ejemplo n.º 4
0
 def run_http_query(self, request_method, data, catch):
     return run_http_query(
         self.schema,
         request_method,
         data,
         query_data=request.args,
         batch_enabled=self.batch,
         catch=catch,
         # Execute options
         root_value=self.get_root_value(),
         context_value=self.get_context(),
         middleware=self.get_middleware(),
         run_sync=not self.enable_async,
     )
Ejemplo n.º 5
0
def test_allows_mutation_to_exist_within_a_get():
    results, params = run_http_query(
        schema,
        "get",
        {},
        query_data=dict(
            query="""
            query TestQuery { test }
            mutation TestMutation { writeTest { test } }
            """,
            operationName="TestQuery",
        ),
    )

    assert as_dicts(results) == [{"data": {"test": "Hello World"}}]
Ejemplo n.º 6
0
def test_allows_sending_a_mutation_via_post():
    results, params = run_http_query(
        schema,
        "post",
        {},
        query_data=dict(query="mutation TestMutation { writeTest { test } }"),
    )

    assert as_dicts(results) == [{
        "data": {
            "writeTest": {
                "test": "Hello World"
            }
        }
    }]
Ejemplo n.º 7
0
def test_handles_field_errors_caught_by_graphql():
    results, params = run_http_query(schema, "get", dict(query="{error}"))

    assert as_dicts(results) == [{
        "data":
        None,
        "errors": [{
            "message": "Throws!",
            "locations": [{
                "line": 1,
                "column": 2
            }],
            "path": ["error"],
        }],
    }]
Ejemplo n.º 8
0
def test_errors_when_missing_operation_name():
    results, params = run_http_query(schema, 'get', {}, query_data=dict(
        query='''
        query TestQuery { test }
        mutation TestMutation { writeTest { test } }
        '''
    ))

    assert executions_to_dict(results) == [{
        'errors': [
            {
                'message': 'Must provide operation name if query contains multiple operations.'
            }
        ]
    }]
Ejemplo n.º 9
0
def test_syntax_error_using_executor_return_promise():
    class TestExecutor(object):
        called = False
        waited = False
        cleaned = False

        def wait_until_finished(self):
            TestExecutor.waited = True

        def clean(self):
            TestExecutor.cleaned = True

        def execute(self, fn, *args, **kwargs):
            TestExecutor.called = True
            return fn(*args, **kwargs)

    query = "this is a syntax error"
    result_promises, params = run_http_query(
        schema,
        "get",
        {},
        dict(query=query),
        executor=TestExecutor(),
        return_promise=True,
    )

    assert isinstance(result_promises, list)
    assert len(result_promises) == 1
    assert isinstance(result_promises[0], Promise)
    results = Promise.all(result_promises).get()

    assert isinstance(results, list)
    assert len(results) == 1
    result = results[0]
    assert isinstance(result, ExecutionResult)

    assert result.data is None
    assert isinstance(result.errors, list)
    assert len(result.errors) == 1
    error = result.errors[0]
    assert isinstance(error, GraphQLSyntaxError)

    assert params == [
        RequestParams(query=query, variables=None, operation_name=None)
    ]
    assert not TestExecutor.called
    assert not TestExecutor.waited
    assert not TestExecutor.cleaned
Ejemplo n.º 10
0
    async def __call__(self, request):
        try:
            data = await self.parse_body(request)
            request_method = request.method.lower()
            is_graphiql = self.is_graphiql(request)
            is_pretty = self.is_pretty(request)

            if request_method == "options":
                return self.process_preflight(request)

            execution_results, all_params = run_http_query(
                self.schema,
                request_method,
                data,
                query_data=request.query,
                batch_enabled=self.batch,
                catch=is_graphiql,
                # Execute options
                root_value=self.root_value,
                context_value=self.get_context(request),
                middleware=self.middleware,
                field_resolver=self.field_resolver,
                **self.execution_options,
            )

            awaited_execution_results = await Promise.all(execution_results)
            result, status_code = encode_execution_results(
                awaited_execution_results,
                is_batch=isinstance(data, list),
                format_error=self.error_formatter,
                encode=partial(self.encoder, pretty=is_pretty),
            )

            if is_graphiql:
                return await self.render_graphiql(params=all_params[0], result=result,)

            return web.Response(
                text=result, status=status_code, content_type="application/json",
            )

        except HttpQueryError as err:
            return web.Response(
                text=self.encoder({"errors": [self.error_formatter(err)]}),
                status=err.status_code,
                headers=err.headers,
                content_type="application/json",
            )
Ejemplo n.º 11
0
def test_allows_get_with_variable_values():
    results, params = run_http_query(
        schema,
        "get",
        {},
        dict(
            query="query helloWho($who: String){ test(who: $who) }",
            variables=json.dumps({"who": "Dolly"}),
        ),
    )

    assert as_dicts(results) == [{
        "data": {
            "test": "Hello Dolly"
        },
        "errors": None
    }]
Ejemplo n.º 12
0
def test_reports_validation_errors():
    results, params = run_http_query(schema, 'get', {}, query_data=dict(
        query='{ test, unknownOne, unknownTwo }'
    ))

    assert executions_to_dict(results) == [{
        'errors': [
            {
                'message': 'Cannot query field "unknownOne" on type "QueryRoot".',
                'locations': [{'line': 1, 'column': 9}]
            },
            {
                'message': 'Cannot query field "unknownTwo" on type "QueryRoot".',
                'locations': [{'line': 1, 'column': 21}]
            }
        ]
    }]
Ejemplo n.º 13
0
def test_errors_when_missing_operation_name():
    results, params = run_http_query(
        schema,
        "get",
        {},
        query_data=dict(query="""
        query TestQuery { test }
        mutation TestMutation { writeTest { test } }
        """),
    )

    assert as_dicts(results) == [{
        "errors": [{
            "message": ("Must provide operation name"
                        " if query contains multiple operations.")
        }]
    }]
    assert isinstance(results[0].errors[0], GraphQLError)
Ejemplo n.º 14
0
    def dispatch_request(self):
        try:
            request_method = request.method.lower()
            data = self.parse_body()

            show_graphiql = request_method == 'get' and self.should_display_graphiql(
            )
            catch = HttpQueryError if show_graphiql else None

            pretty = self.pretty or show_graphiql or request.args.get('pretty')

            execution_results, all_params = run_http_query(
                self.schema,
                request_method,
                data,
                query_data=request.args,
                batch_enabled=self.batch,
                catch=catch,

                # Execute options
                root_value=self.get_root_value(),
                context_value=self.get_context(),
                middleware=self.get_middleware(),
                executor=self.get_executor(),
            )
            result, status_code = encode_execution_results(
                execution_results,
                is_batch=isinstance(data, list),
                format_error=self.format_error,
                encode=partial(self.encode, pretty=pretty))

            if show_graphiql:
                return self.render_graphiql(params=all_params[0],
                                            result=result)

            return Response(status=status_code,
                            response=result,
                            content_type='application/json')

        except HttpQueryError as e:
            return Response(self.encode({'errors': [self.format_error(e)]}),
                            status=e.status_code,
                            headers=e.headers,
                            content_type='application/json')
Ejemplo n.º 15
0
def test_allows_post_with_get_operation_name():
    results, params = run_http_query(
        schema,
        "get",
        data=dict(query="""
            query helloYou { test(who: "You"), ...shared }
            query helloWorld { test(who: "World"), ...shared }
            query helloDolly { test(who: "Dolly"), ...shared }
            fragment shared on QueryRoot {
              shared: test(who: "Everyone")
            }
            """),
        query_data=dict(operationName="helloWorld"),
    )

    assert results == [({
        "test": "Hello World",
        "shared": "Hello Everyone"
    }, None)]
Ejemplo n.º 16
0
def test_allows_get_with_operation_name():
    results, params = run_http_query(schema, 'get', {}, query_data=dict(
        query='''
        query helloYou { test(who: "You"), ...shared }
        query helloWorld { test(who: "World"), ...shared }
        query helloDolly { test(who: "Dolly"), ...shared }
        fragment shared on QueryRoot {
          shared: test(who: "Everyone")
        }
        ''',
        operationName='helloWorld'
    ))

    assert executions_to_dict(results) == [{
        'data': {
            'test': 'Hello World',
            'shared': 'Hello Everyone'
        },
    }]
Ejemplo n.º 17
0
def graphql():
    request_method = request.method.lower()
    if request_method == 'get':
        return render_template(
            'graphiql.html',
            graphiql_version="0.11.11",
            graphiql_html_title="Cyber GraphiQL",
        )

    # token = requestHandler(request)
    token = {'permission': ['view:*']}

    data = load_json_body(request.data.decode())

    pretty = request.args.get('pretty')
    context = {'token': token}

    execution_results, _ = run_http_query(
        schema,
        request_method,
        data,
        query_data=request.args,
        batch_enabled=False,
        catch=False,
        backend=None,

        # Execute options
        root=None,
        context=context,
        middleware=None,
    )

    result, status_code = encode_execution_results(
        execution_results,
        is_batch=False,
        format_error=default_format_error,
        encode=partial(json_encode, pretty=pretty))

    return Response(result,
                    status=status_code,
                    content_type='application/json')
Ejemplo n.º 18
0
def test_batch_allows_post_with_operation_name():
    data = [
        dict(
            query="""
            query helloYou { test(who: "You"), ...shared }
            query helloWorld { test(who: "World"), ...shared }
            query helloDolly { test(who: "Dolly"), ...shared }
            fragment shared on QueryRoot {
              shared: test(who: "Everyone")
            }
            """,
            operationName="helloWorld",
        )
    ]
    data = load_json_body(json_encode(data))
    results, params = run_http_query(schema, "post", data, batch_enabled=True)

    assert results == [({
        "test": "Hello World",
        "shared": "Hello Everyone"
    }, None)]
Ejemplo n.º 19
0
def test_reports_validation_errors():
    results, params = run_http_query(
        schema,
        "get", {},
        query_data=dict(query="{ test, unknownOne, unknownTwo }"))

    assert results == [(
        None,
        [
            {
                "message":
                "Cannot query field 'unknownOne' on type 'QueryRoot'.",
                "locations": [(1, 9)],
            },
            {
                "message":
                "Cannot query field 'unknownTwo' on type 'QueryRoot'.",
                "locations": [(1, 21)],
            },
        ],
    )]
Ejemplo n.º 20
0
def test_get_responses_using_executor_return_promise():
    class TestExecutor(object):
        called = False
        waited = False
        cleaned = False

        def wait_until_finished(self):
            TestExecutor.waited = True

        def clean(self):
            TestExecutor.cleaned = True

        def execute(self, fn, *args, **kwargs):
            TestExecutor.called = True
            return fn(*args, **kwargs)

    query = "{test}"
    result_promises, params = run_http_query(
        schema,
        "get",
        {},
        dict(query=query),
        executor=TestExecutor(),
        return_promise=True,
    )

    assert isinstance(result_promises, list)
    assert len(result_promises) == 1
    assert isinstance(result_promises[0], Promise)
    results = Promise.all(result_promises).get()

    assert as_dicts(results) == [{"data": {"test": "Hello World"}}]
    assert params == [
        RequestParams(query=query, variables=None, operation_name=None)
    ]
    assert TestExecutor.called
    assert not TestExecutor.waited
    assert TestExecutor.cleaned
Ejemplo n.º 21
0
 def _process_request(self, schema, data):
     try:
         request = http.request.httprequest
         context = self._make_context(schema, data)
         execution_results, all_params = run_http_query(
             schema,
             request.method.lower(),
             data,
             query_data=request.args,
             batch_enabled=False,
             catch=False,
             context=context,
         )
         result, status_code = encode_execution_results(
             execution_results,
             is_batch=isinstance(data, list),
             format_error=default_format_error,
             encode=partial(json_encode, pretty=False),
         )
         headers = dict()
         headers["Content-Type"] = "application/json"
         response = http.request.make_response(result, headers=headers)
         response.status_code = status_code
         if any(er.errors for er in execution_results):
             env = http.request.env
             env.cr.rollback()
             env.clear()
         return response
     except HttpQueryError as e:
         result = json_encode({"errors": [default_format_error(e)]})
         headers = dict(e.headers)
         headers["Content-Type"] = "application/json"
         response = http.request.make_response(result, headers=headers)
         response.status_code = e.status_code
         env = http.request.env
         env.cr.rollback()
         env.clear()
         return response
Ejemplo n.º 22
0
    def __call__(self, environ, start_response):
        """Handle request."""
        try:
            headers = [('Content-type', 'application/json; charset=utf-8')]

            request_method = environ['REQUEST_METHOD'].lower()
            data = _parse_body(environ)
            query_data = dict(parse_qsl(environ.get('QUERY_STRING', '')))
            # pass environ to all callable options:
            execute_options = {
                k: v(environ) if callable(v) else v
                for k, v in self.execute_options.items()
            }

            execution_results, all_params = graphql_server.run_http_query(
                self.schema,
                request_method,
                data,
                query_data=query_data,
                **execute_options)

            body, status_code = graphql_server.encode_execution_results(
                execution_results,
                format_error=self.format_error,
                is_batch=isinstance(data, list),
                encode=self.encode)
        except Exception as e:
            print('Error {}'.format(e))
            headers = [('Content-type', 'application/json; charset=utf-8')]
            header_dict = getattr(e, 'headers', None) or {}
            headers += list(header_dict.items())
            status_code = getattr(e, 'status_code', 500)
            errors = [self.format_error(e)]
            body = self.encode({'errors': errors})

        start_response(_status(status_code), headers)
        return [body.encode('utf8')]
Ejemplo n.º 23
0
def test_allows_get_with_operation_name():
    results, params = run_http_query(
        schema,
        "get",
        {},
        query_data=dict(
            query="""
        query helloYou { test(who: "You"), ...shared }
        query helloWorld { test(who: "World"), ...shared }
        query helloDolly { test(who: "Dolly"), ...shared }
        fragment shared on QueryRoot {
          shared: test(who: "Everyone")
        }
        """,
            operationName="helloWorld",
        ),
    )

    assert as_dicts(results) == [{
        "data": {
            "test": "Hello World",
            "shared": "Hello Everyone"
        }
    }]
Ejemplo n.º 24
0
def test_batch_allows_post_with_json_encoding():
    data = load_json_body('[{"query": "{test}"}]')
    results, params = run_http_query(schema, "post", data, batch_enabled=True)

    assert as_dicts(results) == [{"data": {"test": "Hello World"}}]
Ejemplo n.º 25
0
def test_handles_plain_post_text():
    with raises(HttpQueryError) as exc_info:
        run_http_query(schema, "post", {})

    assert exc_info.value == HttpQueryError(400, "Must provide query string.")
Ejemplo n.º 26
0
def test_handles_incomplete_json_bodies():
    with raises(HttpQueryError) as exc_info:
        run_http_query(schema, "post", load_json_body('{"query":'))

    assert exc_info.value == HttpQueryError(400,
                                            "POST body sent invalid JSON.")
Ejemplo n.º 27
0
def test_handles_batch_correctly_if_is_disabled():
    with raises(HttpQueryError) as exc_info:
        run_http_query(schema, "post", [])

    assert exc_info.value == HttpQueryError(
        400, "Batch GraphQL requests are not enabled.")
Ejemplo n.º 28
0
def test_handles_errors_caused_by_a_lack_of_query():
    with raises(HttpQueryError) as exc_info:
        run_http_query(schema, "get", {})

    assert exc_info.value == HttpQueryError(400, "Must provide query string.")
Ejemplo n.º 29
0
def test_not_pretty_data_by_default():
    results, params = run_http_query(schema, "get", dict(query="{test}"))
    body = encode_execution_results(results).body

    assert body == '{"data":{"test":"Hello World"}}'
Ejemplo n.º 30
0
def test_supports_pretty_printing_data():
    results, params = run_http_query(schema, "get", dict(query="{test}"))
    body = encode_execution_results(results, encode=json_encode_pretty).body

    assert body == "{\n" '  "data": {\n' '    "test": "Hello World"\n' "  }\n" "}"
Ejemplo n.º 31
0
def test_allows_post_with_url_encoding():
    results, params = run_http_query(schema,
                                     "post", {},
                                     query_data=dict(query="{test}"))

    assert as_dicts(results) == [{"data": {"test": "Hello World"}}]