diff --git a/gql/gql.py b/gql/gql.py index 903c9609..e35c8045 100644 --- a/gql/gql.py +++ b/gql/gql.py @@ -1,11 +1,13 @@ +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 `, by an :class:`async session ` or by a @@ -13,5 +15,10 @@ def gql(request_string: str) -> DocumentNode: :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) diff --git a/tests/starwars/test_query.py b/tests/starwars/test_query.py index 430aa18e..bf15e11a 100644 --- a/tests/starwars/test_query.py +++ b/tests/starwars/test_query.py @@ -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 @@ -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)