Skip to content

Validate the argument of the gql function #435

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 9, 2023
Merged
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
15 changes: 11 additions & 4 deletions gql/gql.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,24 @@
from __future__ import annotations

from graphql import DocumentNode, Source, parse


def gql(request_string: str) -> DocumentNode:
"""Given a String containing a GraphQL request, parse it into a Document.
def gql(request_string: str | Source) -> DocumentNode:
"""Given a string containing a GraphQL request, parse it into a Document.

:param request_string: the GraphQL request as a String
:type request_string: str
:type request_string: str | Source
:return: a Document which can be later executed or subscribed by a
:class:`Client <gql.client.Client>`, by an
:class:`async session <gql.client.AsyncClientSession>` or by a
:class:`sync session <gql.client.SyncClientSession>`

:raises GraphQLError: if a syntax error is encountered.
"""
source = Source(request_string, "GraphQL request")
if isinstance(request_string, Source):
source = request_string
elif isinstance(request_string, str):
source = Source(request_string, "GraphQL request")
else:
raise TypeError("Request must be passed as a string or Source object.")
return parse(source)
16 changes: 15 additions & 1 deletion tests/starwars/test_query.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import pytest
from graphql import GraphQLError
from graphql import GraphQLError, Source

from gql import Client, gql
from tests.starwars.schema import StarWarsSchema
Expand Down Expand Up @@ -323,3 +323,17 @@ def test_mutation_result(client):
expected = {"createReview": {"stars": 5, "commentary": "This is a great movie!"}}
result = client.execute(query, variable_values=params)
assert result == expected


def test_query_from_source(client):
source = Source("{ hero { name } }")
query = gql(source)
expected = {"hero": {"name": "R2-D2"}}
result = client.execute(query)
assert result == expected


def test_already_parsed_query(client):
query = gql("{ hero { name } }")
with pytest.raises(TypeError, match="must be passed as a string"):
gql(query)