Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/usage/validation.rst
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@ Schema validation
If a GraphQL schema is provided, gql will validate the queries locally before sending them to the backend.
If no schema is provided, gql will send the query to the backend without local validation.

With a schema, pass ``check_required_variables=True`` to ``Client`` to check
that the selected operation has all its required variables before sending the
request. For example, an operation declaring
``$skip: Int!`` needs a ``skip`` key in ``request.variable_values``. You can
omit the key if the operation declares a default, such as ``$skip: Int! = 0``.

You can either provide a schema yourself, or you can request gql to get the schema
from the backend using `introspection`_.

Expand Down
65 changes: 51 additions & 14 deletions gql/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,14 @@
from anyio import fail_after
from graphql import (
ExecutionResult,
GraphQLError,
GraphQLSchema,
IntrospectionQuery,
NonNullTypeNode,
build_ast_schema,
get_operation_ast,
parse,
print_ast,
validate,
)
from tenacity import (
Expand All @@ -50,6 +54,10 @@
log = logging.getLogger(__name__)


class _MissingVariableError(GraphQLError):
"""A required variable was omitted from the request."""


class Client:
"""The Client class is the main entrypoint to execute GraphQL requests
on a GQL transport.
Expand Down Expand Up @@ -83,6 +91,7 @@ def __init__(
parse_results: bool = False,
batch_interval: float = 0,
batch_max: int = 10,
check_required_variables: bool = False,
):
"""Initialize the client with the given parameters.

Expand All @@ -103,6 +112,8 @@ def __init__(
:param batch_interval: Time to wait in seconds for batching requests together.
Batching is disabled (by default) if 0.
:param batch_max: Maximum number of requests in a single batch.
:param check_required_variables: With a schema, check that the selected
operation's required variables are present before sending the request.
"""

if introspection:
Expand Down Expand Up @@ -155,6 +166,7 @@ def __init__(
self.parse_results = parse_results
self.batch_interval = batch_interval
self.batch_max = batch_max
self.check_required_variables = check_required_variables

@property
def batching_enabled(self) -> bool:
Expand All @@ -170,6 +182,29 @@ def validate(self, request: GraphQLRequest) -> None:
if validation_errors:
raise validation_errors[0]

def _validate_request(self, request: GraphQLRequest) -> None:
self.validate(request)
if not self.check_required_variables:
return

operation = get_operation_ast(request.document, request.operation_name)
if operation is None:
return

variable_values = request.variable_values
for definition in operation.variable_definitions or ():
name = definition.variable.name.value
if (
isinstance(definition.type, NonNullTypeNode)
and definition.default_value is None
and (variable_values is None or name not in variable_values)
):
raise _MissingVariableError(
f"Variable '${name}' of required type "
f"'{print_ast(definition.type)}' was not provided.",
definition,
)

def _build_schema_from_introspection(
self, execution_result: ExecutionResult
) -> None:
Expand Down Expand Up @@ -898,9 +933,9 @@ def _execute(
# variable_values and operation_name
request = support_deprecated_request(request, kwargs)

# Validate document
# Validate request
if self.client.schema:
self.client.validate(request)
self.client._validate_request(request)

# Parse variable values for custom scalars if requested
if request.variable_values is not None:
Expand Down Expand Up @@ -1038,12 +1073,12 @@ def _execute_batch(

The extra arguments are passed to the transport execute method."""

# Validate document
# Validate requests
if self.client.schema:

if validate_document:
for req in requests:
self.client.validate(req)
self.client._validate_request(req)

# Parse variable values for custom scalars if requested
if serialize_variables or (
Expand Down Expand Up @@ -1316,9 +1351,9 @@ async def _subscribe(
# variable_values and operation_name
request = support_deprecated_request(request, kwargs)

# Validate document
# Validate request
if self.client.schema:
self.client.validate(request)
self.client._validate_request(request)

# Parse variable values for custom scalars if requested
if request.variable_values is not None:
Expand Down Expand Up @@ -1475,9 +1510,9 @@ async def _execute(
# variable_values and operation_name
request = support_deprecated_request(request, kwargs)

# Validate document
# Validate request
if self.client.schema:
self.client.validate(request)
self.client._validate_request(request)

# Parse variable values for custom scalars if requested
if request.variable_values is not None:
Expand Down Expand Up @@ -1617,12 +1652,12 @@ async def _execute_batch(

The extra arguments are passed to the transport execute_batch method."""

# Validate document
# Validate requests
if self.client.schema:

if validate_document:
for req in requests:
self.client.validate(req)
self.client._validate_request(req)

# Parse variable values for custom scalars if requested
if serialize_variables or (
Expand Down Expand Up @@ -1924,7 +1959,7 @@ def __init__(
if retry_connect is True:
# By default, retry again and again, with maximum 60 seconds
# between retries
self.retry_connect = retry(
self.retry_connect: _Decorator = retry(
retry=retry_if_exception_type(Exception),
wait=wait_exponential(max=60),
)
Expand All @@ -1935,10 +1970,12 @@ def __init__(
self.retry_connect = retry_connect

if retry_execute is True:
# By default, retry 5 times, except if we receive a TransportQueryError
self.retry_execute = retry(
# Skip retries for transport query errors and missing variables.
self.retry_execute: _Decorator = retry(
retry=retry_if_exception_type(Exception)
& retry_unless_exception_type(TransportQueryError),
& retry_unless_exception_type(
(TransportQueryError, _MissingVariableError)
),
stop=stop_after_attempt(5),
wait=wait_exponential(),
)
Expand Down
23 changes: 23 additions & 0 deletions tests/test_async_client_validation.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,37 @@
import asyncio
import json
from unittest.mock import create_autospec

import graphql
import pytest

from gql import Client, gql
from gql.transport import AsyncTransport

from .conftest import MS, WebSocketServerHelper
from .starwars.schema import StarWarsIntrospection, StarWarsSchema, StarWarsTypeDef


@pytest.mark.asyncio
async def test_reconnecting_session_rejects_missing_variable_before_sending():
transport = create_autospec(AsyncTransport, instance=True)
transport.execute.return_value = graphql.ExecutionResult(data={"row": 0})
client = Client(schema="type Query { row(skip: Int!): Int }", transport=transport)
session = await client.connect_async(reconnecting=True, retry_connect=False)
try:
client.check_required_variables = True
request = gql("query Rows($skip: Int!) { row(skip: $skip) }")
with pytest.raises(graphql.GraphQLError, match=r"Variable '\$skip'"):
await session.execute(request)
transport.execute.assert_not_awaited()

request.variable_values = {"skip": 0}
assert await session.execute(request) == {"row": 0}
transport.execute.assert_awaited_once_with(request)
finally:
await client.close_async()


starwars_expected_one = {
"stars": 3,
"commentary": "Was expecting more stuff",
Expand Down
98 changes: 97 additions & 1 deletion tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from unittest import mock

import pytest
from graphql import ExecutionResult, build_ast_schema, parse
from graphql import ExecutionResult, GraphQLError, build_ast_schema, build_schema, parse

from gql import Client, GraphQLRequest, gql
from gql.transport import Transport
Expand Down Expand Up @@ -109,6 +109,102 @@ def test_no_schema_no_transport_exception():
)


@pytest.fixture
def client_with_mock_transport() -> tuple[Client, mock.Mock]:
schema = build_schema("type Query { value(skip: Int!): Int }")
transport = mock.create_autospec(Transport, instance=True)
client = Client(schema=schema, transport=transport)
client.check_required_variables = True
return client, transport


def test_execute_rejects_missing_required_variable(client_with_mock_transport):
client, transport = client_with_mock_transport
transport.execute.return_value = ExecutionResult(data={"value": 1})
request = gql("query ($skip: Int!) { value(skip: $skip) }")

with pytest.raises(GraphQLError, match=r"Variable '\$skip'.*was not provided"):
client.execute(request)

transport.execute.assert_not_called()


def test_execute_batch_rejects_missing_required_variable(client_with_mock_transport):
client, transport = client_with_mock_transport
transport.execute_batch.return_value = [ExecutionResult(data={"value": 1})] * 2
request = gql("query ($skip: Int!) { value(skip: $skip) }")
valid_request = gql("{ value(skip: 0) }")

with pytest.raises(GraphQLError, match=r"Variable '\$skip'.*was not provided"):
client.execute_batch([valid_request, request])

transport.execute_batch.assert_not_called()


def test_execute_batch_validates_variables_for_selected_operation(
client_with_mock_transport,
):
client, transport = client_with_mock_transport
transport.execute_batch.return_value = [
ExecutionResult(data={"value": 1}),
ExecutionResult(data={"value": 0}),
]
document = gql("""
query WithValue($skip: Int!) { value(skip: $skip) }
query WithDefault($skip: Int! = 1) { value(skip: $skip) }
""")
with_default = GraphQLRequest(document, operation_name="WithDefault")
with_value = GraphQLRequest(
document, operation_name="WithValue", variable_values={"skip": 0}
)
requests = [with_default, with_value]

assert client.execute_batch(requests) == [{"value": 1}, {"value": 0}]
transport.execute_batch.assert_called_once_with(requests)


def test_required_variable_check_without_schema():
transport = mock.create_autospec(Transport, instance=True)
transport.execute.return_value = ExecutionResult(data={"value": 1})
client = Client(transport=transport, check_required_variables=True)
request = gql("query ($skip: Int!) { value(skip: $skip) }")

assert client.execute(request) == {"value": 1}
transport.execute.assert_called_once_with(request)


def test_required_variable_check_before_serializing_an_empty_dict():
transport = mock.create_autospec(Transport, instance=True)
client = Client(
schema="type Query { value(skip: Int!): Int }",
transport=transport,
check_required_variables=True,
serialize_variables=True,
)
request = GraphQLRequest(
"query ($skip: Int!) { value(skip: $skip) }", variable_values={}
)

with pytest.raises(GraphQLError, match=r"Variable '\$skip'.*was not provided"):
client.execute(request)
transport.execute.assert_not_called()


def test_required_variable_check_without_selected_operation(client_with_mock_transport):
client, transport = client_with_mock_transport
request = gql("""
query First($skip: Int!) { value(skip: $skip) }
query Second { value(skip: 1) }
""")
transport.execute.return_value = ExecutionResult(
errors=[GraphQLError("Must provide operation name")]
)

with pytest.raises(TransportQueryError, match="Must provide operation name"):
client.execute(request)
transport.execute.assert_called_once_with(request)


@pytest.mark.online
@pytest.mark.requests
def test_execute_result_error():
Expand Down
Loading