File tree Expand file tree Collapse file tree 2 files changed +26
-5
lines changed Expand file tree Collapse file tree 2 files changed +26
-5
lines changed Original file line number Diff line number Diff line change 1+ from __future__ import annotations
2+
13from 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 )
Original file line number Diff line number Diff line change 11import pytest
2- from graphql import GraphQLError
2+ from graphql import GraphQLError , Source
33
44from gql import Client , gql
55from 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 )
You can’t perform that action at this time.
0 commit comments