Skip to content

Commit d14d1f4

Browse files
authored
Modify tests to work with multiple versions of graphql-core (#460)
* Tests modified to work with multiple graphql-core versions regarding braces spaces * Modify gql to work before and after graphql-core 3.3.0a3 subscribe changes
1 parent c23d3e0 commit d14d1f4

File tree

9 files changed

+180
-64
lines changed

9 files changed

+180
-64
lines changed

gql/transport/local_schema.py

+10-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import asyncio
12
from inspect import isawaitable
23
from typing import AsyncGenerator, Awaitable, cast
34

@@ -48,6 +49,12 @@ async def execute(
4849

4950
return execution_result
5051

52+
@staticmethod
53+
async def _await_if_necessary(obj):
54+
"""This method is necessary to work with
55+
graphql-core versions < and >= 3.3.0a3"""
56+
return await obj if asyncio.iscoroutine(obj) else obj
57+
5158
async def subscribe(
5259
self,
5360
document: DocumentNode,
@@ -59,7 +66,9 @@ async def subscribe(
5966
The results are sent as an ExecutionResult object
6067
"""
6168

62-
subscribe_result = subscribe(self.schema, document, *args, **kwargs)
69+
subscribe_result = await self._await_if_necessary(
70+
subscribe(self.schema, document, *args, **kwargs)
71+
)
6372

6473
if isinstance(subscribe_result, ExecutionResult):
6574
yield subscribe_result

tests/conftest.py

+13
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import logging
44
import os
55
import pathlib
6+
import re
67
import ssl
78
import sys
89
import tempfile
@@ -506,3 +507,15 @@ async def run_sync_test_inner(event_loop, server, test_function):
506507
"tests.fixtures.aws.fake_session",
507508
"tests.fixtures.aws.fake_signer",
508509
]
510+
511+
512+
def strip_braces_spaces(s):
513+
"""Allow to ignore differences in graphql-core syntax between versions"""
514+
515+
# Strip spaces after starting braces
516+
strip_front = s.replace("{ ", "{")
517+
518+
# Strip spaces before closing braces only if one space is present
519+
strip_back = re.sub(r"([^\s]) }", r"\1}", strip_front)
520+
521+
return strip_back

tests/custom_scalars/test_json.py

+6-4
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818
from gql import Client, gql
1919
from gql.dsl import DSLSchema
2020

21+
from ..conftest import strip_braces_spaces
22+
2123
# Marking all tests in this file with the aiohttp marker
2224
pytestmark = pytest.mark.aiohttp
2325

@@ -201,9 +203,9 @@ def test_json_value_input_in_dsl_argument():
201203
print(str(query))
202204

203205
assert (
204-
str(query)
206+
strip_braces_spaces(str(query))
205207
== """addPlayer(
206-
player: { name: "Tim", level: 0, is_connected: false, score: 5, friends: ["Lea"] }
208+
player: {name: "Tim", level: 0, is_connected: false, score: 5, friends: ["Lea"]}
207209
)"""
208210
)
209211

@@ -235,8 +237,8 @@ def test_json_value_input_with_none_list_in_dsl_argument():
235237
print(str(query))
236238

237239
assert (
238-
str(query)
240+
strip_braces_spaces(str(query))
239241
== """addPlayer(
240-
player: { name: "Bob", level: 9001, is_connected: true, score: 666.66, friends: null }
242+
player: {name: "Bob", level: 9001, is_connected: true, score: 666.66, friends: null}
241243
)"""
242244
)

tests/starwars/test_dsl.py

+85-7
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
)
3838
from gql.utilities import get_introspection_query_ast, node_tree
3939

40+
from ..conftest import strip_braces_spaces
4041
from .schema import StarWarsSchema
4142

4243

@@ -210,9 +211,9 @@ def test_add_variable_definitions_with_default_value_input_object(ds):
210211
query = dsl_gql(op)
211212

212213
assert (
213-
print_ast(query)
214+
strip_braces_spaces(print_ast(query))
214215
== """
215-
mutation ($review: ReviewInput = { stars: 5, commentary: "Wow!" }, $episode: Episode) {
216+
mutation ($review: ReviewInput = {stars: 5, commentary: "Wow!"}, $episode: Episode) {
216217
createReview(review: $review, episode: $episode) {
217218
stars
218219
commentary
@@ -235,10 +236,10 @@ def test_add_variable_definitions_in_input_object(ds):
235236
query = dsl_gql(op)
236237

237238
assert (
238-
print_ast(query)
239+
strip_braces_spaces(print_ast(query))
239240
== """mutation ($stars: Int, $commentary: String, $episode: Episode) {
240241
createReview(
241-
review: { stars: $stars, commentary: $commentary }
242+
review: {stars: $stars, commentary: $commentary}
242243
episode: $episode
243244
) {
244245
stars
@@ -565,7 +566,7 @@ def test_multiple_operations(ds):
565566
)
566567

567568
assert (
568-
print_ast(query)
569+
strip_braces_spaces(print_ast(query))
569570
== """query GetHeroName {
570571
hero {
571572
name
@@ -575,7 +576,7 @@ def test_multiple_operations(ds):
575576
mutation CreateReviewMutation {
576577
createReview(
577578
episode: JEDI
578-
review: { stars: 5, commentary: "This is a great movie!" }
579+
review: {stars: 5, commentary: "This is a great movie!"}
579580
) {
580581
stars
581582
commentary
@@ -1102,7 +1103,84 @@ def test_node_tree_with_loc(ds):
11021103
<OperationType.QUERY: 'query'>
11031104
""".strip()
11041105

1105-
assert node_tree(document, ignore_loc=False) == node_tree_result
1106+
node_tree_result_stable = """
1107+
DocumentNode
1108+
loc:
1109+
Location
1110+
<Location 0:43>
1111+
definitions:
1112+
OperationDefinitionNode
1113+
loc:
1114+
Location
1115+
<Location 0:43>
1116+
name:
1117+
NameNode
1118+
loc:
1119+
Location
1120+
<Location 6:17>
1121+
value:
1122+
'GetHeroName'
1123+
directives:
1124+
empty tuple
1125+
variable_definitions:
1126+
empty tuple
1127+
selection_set:
1128+
SelectionSetNode
1129+
loc:
1130+
Location
1131+
<Location 18:43>
1132+
selections:
1133+
FieldNode
1134+
loc:
1135+
Location
1136+
<Location 22:41>
1137+
directives:
1138+
empty tuple
1139+
alias:
1140+
None
1141+
name:
1142+
NameNode
1143+
loc:
1144+
Location
1145+
<Location 22:26>
1146+
value:
1147+
'hero'
1148+
arguments:
1149+
empty tuple
1150+
selection_set:
1151+
SelectionSetNode
1152+
loc:
1153+
Location
1154+
<Location 27:41>
1155+
selections:
1156+
FieldNode
1157+
loc:
1158+
Location
1159+
<Location 33:37>
1160+
directives:
1161+
empty tuple
1162+
alias:
1163+
None
1164+
name:
1165+
NameNode
1166+
loc:
1167+
Location
1168+
<Location 33:37>
1169+
value:
1170+
'name'
1171+
arguments:
1172+
empty tuple
1173+
selection_set:
1174+
None
1175+
operation:
1176+
<OperationType.QUERY: 'query'>
1177+
""".strip()
1178+
1179+
try:
1180+
assert node_tree(document, ignore_loc=False) == node_tree_result
1181+
except AssertionError:
1182+
# graphql-core version 3.2.3
1183+
assert node_tree(document, ignore_loc=False) == node_tree_result_stable
11061184

11071185

11081186
def test_legacy_fragment_with_variables(ds):

tests/starwars/test_subscription.py

+17-5
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import asyncio
2+
13
import pytest
24
from graphql import ExecutionResult, GraphQLError, subscribe
35

@@ -17,6 +19,14 @@
1719
"""
1820

1921

22+
async def await_if_coroutine(obj):
23+
"""Function to make tests work for graphql-core versions before and after 3.3.0a3"""
24+
if asyncio.iscoroutine(obj):
25+
return await obj
26+
27+
return obj
28+
29+
2030
@pytest.mark.asyncio
2131
async def test_subscription_support():
2232
# reset review data for this test
@@ -30,7 +40,9 @@ async def test_subscription_support():
3040
params = {"ep": "JEDI"}
3141
expected = [{**review, "episode": "JEDI"} for review in reviews[6]]
3242

33-
ai = subscribe(StarWarsSchema, subs, variable_values=params)
43+
ai = await await_if_coroutine(
44+
subscribe(StarWarsSchema, subs, variable_values=params)
45+
)
3446

3547
result = [result.data["reviewAdded"] async for result in ai]
3648

@@ -53,8 +65,8 @@ async def test_subscription_support_using_client():
5365
async with Client(schema=StarWarsSchema) as session:
5466
results = [
5567
result["reviewAdded"]
56-
async for result in session.subscribe(
57-
subs, variable_values=params, parse_result=False
68+
async for result in await await_if_coroutine(
69+
session.subscribe(subs, variable_values=params, parse_result=False)
5870
)
5971
]
6072

@@ -80,8 +92,8 @@ async def test_subscription_support_using_client_invalid_field():
8092
# We subscribe directly from the transport to avoid local validation
8193
results = [
8294
result
83-
async for result in session.transport.subscribe(
84-
subs, variable_values=params
95+
async for result in await await_if_coroutine(
96+
session.transport.subscribe(subs, variable_values=params)
8597
)
8698
]
8799

tests/test_aiohttp.py

+12-12
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
TransportServerError,
1515
)
1616

17-
from .conftest import TemporaryFile
17+
from .conftest import TemporaryFile, strip_braces_spaces
1818

1919
query1_str = """
2020
query getContinents {
@@ -588,15 +588,15 @@ def test_code():
588588

589589
file_upload_mutation_1 = """
590590
mutation($file: Upload!) {
591-
uploadFile(input:{ other_var:$other_var, file:$file }) {
591+
uploadFile(input:{other_var:$other_var, file:$file}) {
592592
success
593593
}
594594
}
595595
"""
596596

597597
file_upload_mutation_1_operations = (
598-
'{"query": "mutation ($file: Upload!) {\\n uploadFile(input: { other_var: '
599-
'$other_var, file: $file }) {\\n success\\n }\\n}", "variables": '
598+
'{"query": "mutation ($file: Upload!) {\\n uploadFile(input: {other_var: '
599+
'$other_var, file: $file}) {\\n success\\n }\\n}", "variables": '
600600
'{"file": null, "other_var": 42}}'
601601
)
602602

@@ -617,7 +617,7 @@ async def single_upload_handler(request):
617617
field_0 = await reader.next()
618618
assert field_0.name == "operations"
619619
field_0_text = await field_0.text()
620-
assert field_0_text == file_upload_mutation_1_operations
620+
assert strip_braces_spaces(field_0_text) == file_upload_mutation_1_operations
621621

622622
field_1 = await reader.next()
623623
assert field_1.name == "map"
@@ -679,7 +679,7 @@ async def single_upload_handler_with_content_type(request):
679679
field_0 = await reader.next()
680680
assert field_0.name == "operations"
681681
field_0_text = await field_0.text()
682-
assert field_0_text == file_upload_mutation_1_operations
682+
assert strip_braces_spaces(field_0_text) == file_upload_mutation_1_operations
683683

684684
field_1 = await reader.next()
685685
assert field_1.name == "map"
@@ -790,7 +790,7 @@ async def binary_upload_handler(request):
790790
field_0 = await reader.next()
791791
assert field_0.name == "operations"
792792
field_0_text = await field_0.text()
793-
assert field_0_text == file_upload_mutation_1_operations
793+
assert strip_braces_spaces(field_0_text) == file_upload_mutation_1_operations
794794

795795
field_1 = await reader.next()
796796
assert field_1.name == "map"
@@ -931,7 +931,7 @@ async def file_sender(file_name):
931931

932932
file_upload_mutation_2_operations = (
933933
'{"query": "mutation ($file1: Upload!, $file2: Upload!) {\\n '
934-
'uploadFile(input: { file1: $file, file2: $file }) {\\n success\\n }\\n}", '
934+
'uploadFile(input: {file1: $file, file2: $file}) {\\n success\\n }\\n}", '
935935
'"variables": {"file1": null, "file2": null}}'
936936
)
937937

@@ -955,7 +955,7 @@ async def handler(request):
955955
field_0 = await reader.next()
956956
assert field_0.name == "operations"
957957
field_0_text = await field_0.text()
958-
assert field_0_text == file_upload_mutation_2_operations
958+
assert strip_braces_spaces(field_0_text) == file_upload_mutation_2_operations
959959

960960
field_1 = await reader.next()
961961
assert field_1.name == "map"
@@ -1019,15 +1019,15 @@ async def handler(request):
10191019

10201020
file_upload_mutation_3 = """
10211021
mutation($files: [Upload!]!) {
1022-
uploadFiles(input:{ files:$files }) {
1022+
uploadFiles(input:{files:$files}) {
10231023
success
10241024
}
10251025
}
10261026
"""
10271027

10281028
file_upload_mutation_3_operations = (
10291029
'{"query": "mutation ($files: [Upload!]!) {\\n uploadFiles('
1030-
"input: { files: $files })"
1030+
"input: {files: $files})"
10311031
' {\\n success\\n }\\n}", "variables": {"files": [null, null]}}'
10321032
)
10331033

@@ -1046,7 +1046,7 @@ async def handler(request):
10461046
field_0 = await reader.next()
10471047
assert field_0.name == "operations"
10481048
field_0_text = await field_0.text()
1049-
assert field_0_text == file_upload_mutation_3_operations
1049+
assert strip_braces_spaces(field_0_text) == file_upload_mutation_3_operations
10501050

10511051
field_1 = await reader.next()
10521052
assert field_1.name == "map"

0 commit comments

Comments
 (0)