Skip to content

Commit dfbcb59

Browse files
authored
Validate the argument of the gql function (#435)
1 parent d4c9751 commit dfbcb59

File tree

2 files changed

+26
-5
lines changed

2 files changed

+26
-5
lines changed

gql/gql.py

+11-4
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,24 @@
1+
from __future__ import annotations
2+
13
from graphql import DocumentNode, Source, parse
24

35

4-
def gql(request_string: str) -> DocumentNode:
5-
"""Given a String containing a GraphQL request, parse it into a Document.
6+
def gql(request_string: str | Source) -> DocumentNode:
7+
"""Given a string containing a GraphQL request, parse it into a Document.
68
79
:param request_string: the GraphQL request as a String
8-
:type request_string: str
10+
:type request_string: str | Source
911
:return: a Document which can be later executed or subscribed by a
1012
:class:`Client <gql.client.Client>`, by an
1113
:class:`async session <gql.client.AsyncClientSession>` or by a
1214
:class:`sync session <gql.client.SyncClientSession>`
1315
1416
:raises GraphQLError: if a syntax error is encountered.
1517
"""
16-
source = Source(request_string, "GraphQL request")
18+
if isinstance(request_string, Source):
19+
source = request_string
20+
elif isinstance(request_string, str):
21+
source = Source(request_string, "GraphQL request")
22+
else:
23+
raise TypeError("Request must be passed as a string or Source object.")
1724
return parse(source)

tests/starwars/test_query.py

+15-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import pytest
2-
from graphql import GraphQLError
2+
from graphql import GraphQLError, Source
33

44
from gql import Client, gql
55
from tests.starwars.schema import StarWarsSchema
@@ -323,3 +323,17 @@ def test_mutation_result(client):
323323
expected = {"createReview": {"stars": 5, "commentary": "This is a great movie!"}}
324324
result = client.execute(query, variable_values=params)
325325
assert result == expected
326+
327+
328+
def test_query_from_source(client):
329+
source = Source("{ hero { name } }")
330+
query = gql(source)
331+
expected = {"hero": {"name": "R2-D2"}}
332+
result = client.execute(query)
333+
assert result == expected
334+
335+
336+
def test_already_parsed_query(client):
337+
query = gql("{ hero { name } }")
338+
with pytest.raises(TypeError, match="must be passed as a string"):
339+
gql(query)

0 commit comments

Comments
 (0)