Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions gql/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -498,6 +498,7 @@ async def main(args: Namespace) -> int:
) as session:

if args.print_schema:
assert session.client.schema is not None
schema_str = print_schema(session.client.schema)
print(schema_str)

Expand Down
57 changes: 30 additions & 27 deletions gql/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
Generator,
List,
Literal,
NoReturn,
Optional,
Tuple,
TypeVar,
Expand Down Expand Up @@ -736,11 +737,8 @@ def subscribe(
generator_task = asyncio.ensure_future(
async_generator.__anext__(), loop=loop
)
result: Union[
Dict[str, Any], ExecutionResult
] = loop.run_until_complete(
generator_task
) # type: ignore
result = loop.run_until_complete(generator_task)
assert isinstance(result, (dict, ExecutionResult))
yield result

except StopAsyncIteration:
Expand All @@ -757,7 +755,9 @@ def subscribe(
# Then reraise the exception
raise

async def connect_async(self, reconnecting=False, **kwargs):
async def connect_async(
self, reconnecting: bool = False, **kwargs: Any
) -> "AsyncClientSession":
r"""Connect asynchronously with the underlying async transport to
produce a session.

Expand Down Expand Up @@ -800,18 +800,19 @@ async def connect_async(self, reconnecting=False, **kwargs):

return self.session

async def close_async(self):
async def close_async(self) -> None:
"""Close the async transport and stop the optional reconnecting task."""
assert isinstance(self.session, AsyncClientSession)

await self.session.close()

async def __aenter__(self):
async def __aenter__(self) -> "AsyncClientSession":
return await self.connect_async()

async def __aexit__(self, exc_type, exc, tb):
async def __aexit__(self, *args: Any) -> None:
await self.close_async()

def connect_sync(self):
def connect_sync(self) -> "SyncClientSession":
r"""Connect synchronously with the underlying sync transport to
produce a session.

Expand Down Expand Up @@ -845,7 +846,7 @@ def connect_sync(self):

return self.session

def close_sync(self):
def close_sync(self) -> None:
"""Close the sync session and the sync transport.

If batching is enabled, this will block until the remaining queries in the
Expand All @@ -855,10 +856,10 @@ def close_sync(self):

self.session.close()

def __enter__(self):
def __enter__(self) -> "SyncClientSession":
return self.connect_sync()

def __exit__(self, *args):
def __exit__(self, *args: Any) -> None:
self.close_sync()


Expand Down Expand Up @@ -1228,7 +1229,7 @@ def _execute_future(

return future

def connect(self):
def connect(self) -> None:
"""Connect the transport and initialize the batch threading loop if batching
is enabled."""

Expand All @@ -1241,7 +1242,7 @@ def connect(self):

self.transport.connect()

def close(self):
def close(self) -> None:
"""Close the transport and cleanup the batching thread if batching is enabled.

Will wait until all the remaining requests in the batch processing queue
Expand Down Expand Up @@ -1271,7 +1272,8 @@ def fetch_schema(self) -> None:
self.client._build_schema_from_introspection(execution_result)

@property
def transport(self):
def transport(self) -> Transport:
assert isinstance(self.client.transport, Transport)
return self.client.transport


Expand Down Expand Up @@ -1825,15 +1827,15 @@ async def _execute_future(

return future

async def _batch_init(self):
async def _batch_init(self) -> None:
"""Initialize the batch task loop if batching is enabled."""
if self.client.batching_enabled:
self.batch_queue: asyncio.Queue = asyncio.Queue()
self._batch_task_stop_requested = False
self._batch_task_stopped_event = asyncio.Event()
self._batch_task = asyncio.create_task(self._batch_loop())

async def _batch_cleanup(self):
async def _batch_cleanup(self) -> None:
"""Cleanup the batching task if batching is enabled."""
if hasattr(self, "_batch_task_stopped_event"):
# Send a None in the queue to indicate that the batching task must stop
Expand All @@ -1844,7 +1846,7 @@ async def _batch_cleanup(self):
# Wait for the task to process remaining requests and stop
await self._batch_task_stopped_event.wait()

async def connect(self):
async def connect(self) -> None:
"""Connect the transport and initialize the batch task loop if batching
is enabled."""

Expand All @@ -1856,7 +1858,7 @@ async def connect(self):
await self.transport.close()
raise e

async def close(self):
async def close(self) -> None:
"""Close the transport and cleanup the batching task if batching is enabled.

Will wait until all the remaining requests in the batch processing queue
Expand All @@ -1881,7 +1883,8 @@ async def fetch_schema(self) -> None:
self.client._build_schema_from_introspection(execution_result)

@property
def transport(self):
def transport(self) -> AsyncTransport:
assert isinstance(self.client.transport, AsyncTransport)
return self.client.transport


Expand Down Expand Up @@ -1916,7 +1919,7 @@ def __init__(
to provide specific retries parameters for this method.
"""
self.client = client
self._connect_task = None
self._connect_task: Optional[asyncio.Task[Any]] = None

self._reconnect_request_event = asyncio.Event()
self._connected_event = asyncio.Event()
Expand Down Expand Up @@ -1955,7 +1958,7 @@ def __init__(
self._execute_with_retries = self.retry_execute(self._execute_once)
self._connect_with_retries = self.retry_connect(self.transport.connect)

async def _connection_loop(self):
async def _connection_loop(self) -> NoReturn:
"""Coroutine used for the connection task.

- try to connect to the transport with retries
Expand All @@ -1977,7 +1980,7 @@ async def _connection_loop(self):
await self._reconnect_request_event.wait()
await self.transport.close()

async def start_connecting_task(self):
async def start_connecting_task(self) -> None:
"""Start the task responsible to restart the connection
of the transport when requested by an event.
"""
Expand All @@ -1988,21 +1991,21 @@ async def start_connecting_task(self):

await self._connected_event.wait()

async def stop_connecting_task(self):
async def stop_connecting_task(self) -> None:
"""Stop the connecting task."""
if self._connect_task is not None:
self._connect_task.cancel()
self._connect_task = None

async def connect(self):
async def connect(self) -> None:
"""Start the connect task and initialize the batch task loop if batching
is enabled."""

await self._batch_init()

await self.start_connecting_task()

async def close(self):
async def close(self) -> None:
"""Stop the connect task and cleanup the batching task
if batching is enabled."""
await self._batch_cleanup()
Expand Down
10 changes: 7 additions & 3 deletions tests/custom_scalars/test_money.py
Original file line number Diff line number Diff line change
Expand Up @@ -615,16 +615,19 @@ async def test_custom_scalar_serialize_variables_schema_from_introspection(

schema = session.client.schema

assert schema is not None

# Updating the Money Scalar in the schema
# We cannot replace it because some other objects keep a reference
# to the existing Scalar
# cannot do: schema.type_map["Money"] = MoneyScalar

money_scalar = schema.type_map["Money"]

money_scalar.serialize = MoneyScalar.serialize
money_scalar.parse_value = MoneyScalar.parse_value
money_scalar.parse_literal = MoneyScalar.parse_literal
assert isinstance(money_scalar, GraphQLScalarType)
money_scalar.serialize = MoneyScalar.serialize # type: ignore
money_scalar.parse_value = MoneyScalar.parse_value # type: ignore
money_scalar.parse_literal = MoneyScalar.parse_literal # type: ignore

query = gql("query myquery($money: Money) {toEuros(money: $money)}")

Expand All @@ -646,6 +649,7 @@ async def test_update_schema_scalars(aiohttp_server):
# Update the schema MoneyScalar default implementation from
# introspection with our provided conversion methods
# update_schema_scalars(session.client.schema, [MoneyScalar])
assert session.client.schema is not None
update_schema_scalar(session.client.schema, "Money", MoneyScalar)

query = gql("query myquery($money: Money) {toEuros(money: $money)}")
Expand Down
3 changes: 3 additions & 0 deletions tests/starwars/test_introspection.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ async def test_starwars_introspection_args(aiohttp_server):
},
) as session:

assert session.client.schema is not None
schema_str = print_schema(session.client.schema)
print(schema_str)

Expand All @@ -42,6 +43,7 @@ async def test_starwars_introspection_args(aiohttp_server):
},
) as session:

assert session.client.schema is not None
schema_str = print_schema(session.client.schema)
print(schema_str)

Expand All @@ -56,6 +58,7 @@ async def test_starwars_introspection_args(aiohttp_server):
fetch_schema_from_transport=True,
) as session:

assert session.client.schema is not None
schema_str = print_schema(session.client.schema)
print(schema_str)

Expand Down
11 changes: 9 additions & 2 deletions tests/test_aiohttp.py
Original file line number Diff line number Diff line change
Expand Up @@ -1412,6 +1412,7 @@ async def handler(request):

execution_result = await session.execute(query, get_execution_result=True)

assert execution_result.extensions is not None
assert execution_result.extensions["key1"] == "val1"


Expand Down Expand Up @@ -1612,6 +1613,7 @@ async def handler(request):
async def test_aiohttp_reconnecting_session_retries(aiohttp_server, retries):
from aiohttp import web

from gql.client import ReconnectingAsyncClientSession
from gql.transport.aiohttp import AIOHTTPTransport

async def handler(request):
Expand All @@ -1634,6 +1636,8 @@ async def handler(request):
reconnecting=True, retry_execute=retries, retry_connect=retries
)

assert isinstance(session, ReconnectingAsyncClientSession)

assert session._execute_with_retries == session._execute_once
assert session._connect_with_retries == session.transport.connect

Expand All @@ -1646,6 +1650,7 @@ async def test_aiohttp_reconnecting_session_start_connecting_task_twice(
):
from aiohttp import web

from gql.client import ReconnectingAsyncClientSession
from gql.transport.aiohttp import AIOHTTPTransport

async def handler(request):
Expand All @@ -1666,6 +1671,8 @@ async def handler(request):

session = await client.connect_async(reconnecting=True)

assert isinstance(session, ReconnectingAsyncClientSession)

await session.start_connecting_task()

print(f"Captured log: {caplog.text}")
Expand Down Expand Up @@ -1847,7 +1854,7 @@ async def handler(request):
DeprecationWarning,
match="Using a DocumentNode is deprecated",
):
result = await session.execute(query.document)
result = await session.execute(query.document) # type: ignore

continents = result["continents"]

Expand Down Expand Up @@ -1915,6 +1922,6 @@ async def handler(request):
async with Client(transport=transport) as session:

with pytest.raises(TypeError) as exc_info:
await session.execute("qmlsdkfj")
await session.execute("qmlsdkfj") # type: ignore[call-overload]

assert "request should be a GraphQLRequest object" in str(exc_info.value)
1 change: 1 addition & 0 deletions tests/test_aiohttp_batch.py
Original file line number Diff line number Diff line change
Expand Up @@ -520,6 +520,7 @@ async def handler(request):
query, get_execution_result=True
)

assert execution_results[0].extensions is not None
assert execution_results[0].extensions["key1"] == "val1"


Expand Down
4 changes: 4 additions & 0 deletions tests/test_aiohttp_websocket_subscription.py
Original file line number Diff line number Diff line change
Expand Up @@ -811,6 +811,9 @@ async def test_subscribe_on_closing_transport(server, subscription_str):
subscription = gql(subscription_str.format(count=count))

async with client as session:
assert isinstance(session.transport, AIOHTTPWebsocketsTransport)
assert session.transport.adapter.websocket is not None

session.transport.adapter.websocket._writer._closing = True

with pytest.raises(TransportConnectionFailed):
Expand All @@ -834,6 +837,7 @@ async def test_subscribe_on_null_transport(server, subscription_str):
subscription = gql(subscription_str.format(count=count))

async with client as session:
assert isinstance(session.transport, AIOHTTPWebsocketsTransport)

session.transport.adapter.websocket = None
with pytest.raises(TransportConnectionFailed):
Expand Down
2 changes: 2 additions & 0 deletions tests/test_appsync_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,10 +66,12 @@ async def handler(request):
execution_result = await session.execute(query, get_execution_result=True)

result = execution_result.data
assert result is not None
message = result["createMessage"]["message"]

assert message == "Hello world!"

assert execution_result.extensions is not None
sent_headers = execution_result.extensions["received_headers"]

assert sent_headers["X-Amz-Security-Token"] == "fake-token"
Expand Down
2 changes: 2 additions & 0 deletions tests/test_appsync_websockets.py
Original file line number Diff line number Diff line change
Expand Up @@ -699,13 +699,15 @@ async def test_appsync_subscription_variable_values_and_operation_name(server):
):

result = execution_result.data
assert result is not None
message = result["onCreateMessage"]["message"]
print(f"Message received: '{message}'")

received_messages.append(message)

print(f"extensions received: {execution_result.extensions}")

assert execution_result.extensions is not None
assert execution_result.extensions["operation_name"] == "onCreateMessage"
variables = execution_result.extensions["variables"]
assert variables["key1"] == "val1"
Expand Down
1 change: 1 addition & 0 deletions tests/test_httpx.py
Original file line number Diff line number Diff line change
Expand Up @@ -556,6 +556,7 @@ def test_code():

execution_result = session.execute(query, get_execution_result=True)

assert execution_result.extensions is not None
assert execution_result.extensions["key1"] == "val1"

await run_sync_test(server, test_code)
Expand Down
Loading
Loading