Skip to content

Commit

Permalink
Modify tests to work with multiple versions of graphql-core (#460)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
leszekhanusz committed Jan 3, 2024
1 parent c23d3e0 commit d14d1f4
Show file tree
Hide file tree
Showing 9 changed files with 180 additions and 64 deletions.
11 changes: 10 additions & 1 deletion gql/transport/local_schema.py
@@ -1,3 +1,4 @@
import asyncio
from inspect import isawaitable
from typing import AsyncGenerator, Awaitable, cast

Expand Down Expand Up @@ -48,6 +49,12 @@ async def execute(

return execution_result

@staticmethod
async def _await_if_necessary(obj):
"""This method is necessary to work with
graphql-core versions < and >= 3.3.0a3"""
return await obj if asyncio.iscoroutine(obj) else obj

async def subscribe(
self,
document: DocumentNode,
Expand All @@ -59,7 +66,9 @@ async def subscribe(
The results are sent as an ExecutionResult object
"""

subscribe_result = subscribe(self.schema, document, *args, **kwargs)
subscribe_result = await self._await_if_necessary(
subscribe(self.schema, document, *args, **kwargs)
)

if isinstance(subscribe_result, ExecutionResult):
yield subscribe_result
Expand Down
13 changes: 13 additions & 0 deletions tests/conftest.py
Expand Up @@ -3,6 +3,7 @@
import logging
import os
import pathlib
import re
import ssl
import sys
import tempfile
Expand Down Expand Up @@ -506,3 +507,15 @@ async def run_sync_test_inner(event_loop, server, test_function):
"tests.fixtures.aws.fake_session",
"tests.fixtures.aws.fake_signer",
]


def strip_braces_spaces(s):
"""Allow to ignore differences in graphql-core syntax between versions"""

# Strip spaces after starting braces
strip_front = s.replace("{ ", "{")

# Strip spaces before closing braces only if one space is present
strip_back = re.sub(r"([^\s]) }", r"\1}", strip_front)

return strip_back
10 changes: 6 additions & 4 deletions tests/custom_scalars/test_json.py
Expand Up @@ -18,6 +18,8 @@
from gql import Client, gql
from gql.dsl import DSLSchema

from ..conftest import strip_braces_spaces

# Marking all tests in this file with the aiohttp marker
pytestmark = pytest.mark.aiohttp

Expand Down Expand Up @@ -201,9 +203,9 @@ def test_json_value_input_in_dsl_argument():
print(str(query))

assert (
str(query)
strip_braces_spaces(str(query))
== """addPlayer(
player: { name: "Tim", level: 0, is_connected: false, score: 5, friends: ["Lea"] }
player: {name: "Tim", level: 0, is_connected: false, score: 5, friends: ["Lea"]}
)"""
)

Expand Down Expand Up @@ -235,8 +237,8 @@ def test_json_value_input_with_none_list_in_dsl_argument():
print(str(query))

assert (
str(query)
strip_braces_spaces(str(query))
== """addPlayer(
player: { name: "Bob", level: 9001, is_connected: true, score: 666.66, friends: null }
player: {name: "Bob", level: 9001, is_connected: true, score: 666.66, friends: null}
)"""
)
92 changes: 85 additions & 7 deletions tests/starwars/test_dsl.py
Expand Up @@ -37,6 +37,7 @@
)
from gql.utilities import get_introspection_query_ast, node_tree

from ..conftest import strip_braces_spaces
from .schema import StarWarsSchema


Expand Down Expand Up @@ -210,9 +211,9 @@ def test_add_variable_definitions_with_default_value_input_object(ds):
query = dsl_gql(op)

assert (
print_ast(query)
strip_braces_spaces(print_ast(query))
== """
mutation ($review: ReviewInput = { stars: 5, commentary: "Wow!" }, $episode: Episode) {
mutation ($review: ReviewInput = {stars: 5, commentary: "Wow!"}, $episode: Episode) {
createReview(review: $review, episode: $episode) {
stars
commentary
Expand All @@ -235,10 +236,10 @@ def test_add_variable_definitions_in_input_object(ds):
query = dsl_gql(op)

assert (
print_ast(query)
strip_braces_spaces(print_ast(query))
== """mutation ($stars: Int, $commentary: String, $episode: Episode) {
createReview(
review: { stars: $stars, commentary: $commentary }
review: {stars: $stars, commentary: $commentary}
episode: $episode
) {
stars
Expand Down Expand Up @@ -565,7 +566,7 @@ def test_multiple_operations(ds):
)

assert (
print_ast(query)
strip_braces_spaces(print_ast(query))
== """query GetHeroName {
hero {
name
Expand All @@ -575,7 +576,7 @@ def test_multiple_operations(ds):
mutation CreateReviewMutation {
createReview(
episode: JEDI
review: { stars: 5, commentary: "This is a great movie!" }
review: {stars: 5, commentary: "This is a great movie!"}
) {
stars
commentary
Expand Down Expand Up @@ -1102,7 +1103,84 @@ def test_node_tree_with_loc(ds):
<OperationType.QUERY: 'query'>
""".strip()

assert node_tree(document, ignore_loc=False) == node_tree_result
node_tree_result_stable = """
DocumentNode
loc:
Location
<Location 0:43>
definitions:
OperationDefinitionNode
loc:
Location
<Location 0:43>
name:
NameNode
loc:
Location
<Location 6:17>
value:
'GetHeroName'
directives:
empty tuple
variable_definitions:
empty tuple
selection_set:
SelectionSetNode
loc:
Location
<Location 18:43>
selections:
FieldNode
loc:
Location
<Location 22:41>
directives:
empty tuple
alias:
None
name:
NameNode
loc:
Location
<Location 22:26>
value:
'hero'
arguments:
empty tuple
selection_set:
SelectionSetNode
loc:
Location
<Location 27:41>
selections:
FieldNode
loc:
Location
<Location 33:37>
directives:
empty tuple
alias:
None
name:
NameNode
loc:
Location
<Location 33:37>
value:
'name'
arguments:
empty tuple
selection_set:
None
operation:
<OperationType.QUERY: 'query'>
""".strip()

try:
assert node_tree(document, ignore_loc=False) == node_tree_result
except AssertionError:
# graphql-core version 3.2.3
assert node_tree(document, ignore_loc=False) == node_tree_result_stable


def test_legacy_fragment_with_variables(ds):
Expand Down
22 changes: 17 additions & 5 deletions tests/starwars/test_subscription.py
@@ -1,3 +1,5 @@
import asyncio

import pytest
from graphql import ExecutionResult, GraphQLError, subscribe

Expand All @@ -17,6 +19,14 @@
"""


async def await_if_coroutine(obj):
"""Function to make tests work for graphql-core versions before and after 3.3.0a3"""
if asyncio.iscoroutine(obj):
return await obj

return obj


@pytest.mark.asyncio
async def test_subscription_support():
# reset review data for this test
Expand All @@ -30,7 +40,9 @@ async def test_subscription_support():
params = {"ep": "JEDI"}
expected = [{**review, "episode": "JEDI"} for review in reviews[6]]

ai = subscribe(StarWarsSchema, subs, variable_values=params)
ai = await await_if_coroutine(
subscribe(StarWarsSchema, subs, variable_values=params)
)

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

Expand All @@ -53,8 +65,8 @@ async def test_subscription_support_using_client():
async with Client(schema=StarWarsSchema) as session:
results = [
result["reviewAdded"]
async for result in session.subscribe(
subs, variable_values=params, parse_result=False
async for result in await await_if_coroutine(
session.subscribe(subs, variable_values=params, parse_result=False)
)
]

Expand All @@ -80,8 +92,8 @@ async def test_subscription_support_using_client_invalid_field():
# We subscribe directly from the transport to avoid local validation
results = [
result
async for result in session.transport.subscribe(
subs, variable_values=params
async for result in await await_if_coroutine(
session.transport.subscribe(subs, variable_values=params)
)
]

Expand Down
24 changes: 12 additions & 12 deletions tests/test_aiohttp.py
Expand Up @@ -14,7 +14,7 @@
TransportServerError,
)

from .conftest import TemporaryFile
from .conftest import TemporaryFile, strip_braces_spaces

query1_str = """
query getContinents {
Expand Down Expand Up @@ -588,15 +588,15 @@ def test_code():

file_upload_mutation_1 = """
mutation($file: Upload!) {
uploadFile(input:{ other_var:$other_var, file:$file }) {
uploadFile(input:{other_var:$other_var, file:$file}) {
success
}
}
"""

file_upload_mutation_1_operations = (
'{"query": "mutation ($file: Upload!) {\\n uploadFile(input: { other_var: '
'$other_var, file: $file }) {\\n success\\n }\\n}", "variables": '
'{"query": "mutation ($file: Upload!) {\\n uploadFile(input: {other_var: '
'$other_var, file: $file}) {\\n success\\n }\\n}", "variables": '
'{"file": null, "other_var": 42}}'
)

Expand All @@ -617,7 +617,7 @@ async def single_upload_handler(request):
field_0 = await reader.next()
assert field_0.name == "operations"
field_0_text = await field_0.text()
assert field_0_text == file_upload_mutation_1_operations
assert strip_braces_spaces(field_0_text) == file_upload_mutation_1_operations

field_1 = await reader.next()
assert field_1.name == "map"
Expand Down Expand Up @@ -679,7 +679,7 @@ async def single_upload_handler_with_content_type(request):
field_0 = await reader.next()
assert field_0.name == "operations"
field_0_text = await field_0.text()
assert field_0_text == file_upload_mutation_1_operations
assert strip_braces_spaces(field_0_text) == file_upload_mutation_1_operations

field_1 = await reader.next()
assert field_1.name == "map"
Expand Down Expand Up @@ -790,7 +790,7 @@ async def binary_upload_handler(request):
field_0 = await reader.next()
assert field_0.name == "operations"
field_0_text = await field_0.text()
assert field_0_text == file_upload_mutation_1_operations
assert strip_braces_spaces(field_0_text) == file_upload_mutation_1_operations

field_1 = await reader.next()
assert field_1.name == "map"
Expand Down Expand Up @@ -931,7 +931,7 @@ async def file_sender(file_name):

file_upload_mutation_2_operations = (
'{"query": "mutation ($file1: Upload!, $file2: Upload!) {\\n '
'uploadFile(input: { file1: $file, file2: $file }) {\\n success\\n }\\n}", '
'uploadFile(input: {file1: $file, file2: $file}) {\\n success\\n }\\n}", '
'"variables": {"file1": null, "file2": null}}'
)

Expand All @@ -955,7 +955,7 @@ async def handler(request):
field_0 = await reader.next()
assert field_0.name == "operations"
field_0_text = await field_0.text()
assert field_0_text == file_upload_mutation_2_operations
assert strip_braces_spaces(field_0_text) == file_upload_mutation_2_operations

field_1 = await reader.next()
assert field_1.name == "map"
Expand Down Expand Up @@ -1019,15 +1019,15 @@ async def handler(request):

file_upload_mutation_3 = """
mutation($files: [Upload!]!) {
uploadFiles(input:{ files:$files }) {
uploadFiles(input:{files:$files}) {
success
}
}
"""

file_upload_mutation_3_operations = (
'{"query": "mutation ($files: [Upload!]!) {\\n uploadFiles('
"input: { files: $files })"
"input: {files: $files})"
' {\\n success\\n }\\n}", "variables": {"files": [null, null]}}'
)

Expand All @@ -1046,7 +1046,7 @@ async def handler(request):
field_0 = await reader.next()
assert field_0.name == "operations"
field_0_text = await field_0.text()
assert field_0_text == file_upload_mutation_3_operations
assert strip_braces_spaces(field_0_text) == file_upload_mutation_3_operations

field_1 = await reader.next()
assert field_1.name == "map"
Expand Down

0 comments on commit d14d1f4

Please sign in to comment.