diff --git a/gql/cli.py b/gql/cli.py index 01dfb20f..ca989abd 100644 --- a/gql/cli.py +++ b/gql/cli.py @@ -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) diff --git a/gql/client.py b/gql/client.py index eec79b8d..0eed420c 100644 --- a/gql/client.py +++ b/gql/client.py @@ -13,6 +13,7 @@ Generator, List, Literal, + NoReturn, Optional, Tuple, TypeVar, @@ -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: @@ -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. @@ -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. @@ -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 @@ -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() @@ -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.""" @@ -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 @@ -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 @@ -1825,7 +1827,7 @@ 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() @@ -1833,7 +1835,7 @@ async def _batch_init(self): 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 @@ -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.""" @@ -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 @@ -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 @@ -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() @@ -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 @@ -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. """ @@ -1988,13 +1991,13 @@ 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.""" @@ -2002,7 +2005,7 @@ async def connect(self): 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() diff --git a/tests/custom_scalars/test_money.py b/tests/custom_scalars/test_money.py index 8b3971e5..2810de83 100644 --- a/tests/custom_scalars/test_money.py +++ b/tests/custom_scalars/test_money.py @@ -615,6 +615,8 @@ 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 @@ -622,9 +624,10 @@ async def test_custom_scalar_serialize_variables_schema_from_introspection( 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)}") @@ -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)}") diff --git a/tests/starwars/test_introspection.py b/tests/starwars/test_introspection.py index 9e5ff4aa..7790deb1 100644 --- a/tests/starwars/test_introspection.py +++ b/tests/starwars/test_introspection.py @@ -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) @@ -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) @@ -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) diff --git a/tests/test_aiohttp.py b/tests/test_aiohttp.py index 00bd8a0f..fe319fd4 100644 --- a/tests/test_aiohttp.py +++ b/tests/test_aiohttp.py @@ -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" @@ -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): @@ -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 @@ -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): @@ -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}") @@ -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"] @@ -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) diff --git a/tests/test_aiohttp_batch.py b/tests/test_aiohttp_batch.py index 37d8f64e..71d69aa6 100644 --- a/tests/test_aiohttp_batch.py +++ b/tests/test_aiohttp_batch.py @@ -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" diff --git a/tests/test_aiohttp_websocket_subscription.py b/tests/test_aiohttp_websocket_subscription.py index 658e3eff..0d443c1b 100644 --- a/tests/test_aiohttp_websocket_subscription.py +++ b/tests/test_aiohttp_websocket_subscription.py @@ -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): @@ -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): diff --git a/tests/test_appsync_http.py b/tests/test_appsync_http.py index c080da46..7507bd9a 100644 --- a/tests/test_appsync_http.py +++ b/tests/test_appsync_http.py @@ -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" diff --git a/tests/test_appsync_websockets.py b/tests/test_appsync_websockets.py index 2103db8f..8f3f077a 100644 --- a/tests/test_appsync_websockets.py +++ b/tests/test_appsync_websockets.py @@ -699,6 +699,7 @@ 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}'") @@ -706,6 +707,7 @@ async def test_appsync_subscription_variable_values_and_operation_name(server): 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" diff --git a/tests/test_httpx.py b/tests/test_httpx.py index 88612464..d32069d7 100644 --- a/tests/test_httpx.py +++ b/tests/test_httpx.py @@ -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) diff --git a/tests/test_httpx_async.py b/tests/test_httpx_async.py index 5effea79..bbc0205f 100644 --- a/tests/test_httpx_async.py +++ b/tests/test_httpx_async.py @@ -1108,6 +1108,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" @@ -1293,6 +1294,7 @@ async def handler(request): async def test_httpx_reconnecting_session_retries(aiohttp_server, retries): from aiohttp import web + from gql.client import ReconnectingAsyncClientSession from gql.transport.httpx import HTTPXAsyncTransport async def handler(request): @@ -1315,6 +1317,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 @@ -1328,6 +1332,7 @@ async def test_httpx_reconnecting_session_start_connecting_task_twice( ): from aiohttp import web + from gql.client import ReconnectingAsyncClientSession from gql.transport.httpx import HTTPXAsyncTransport async def handler(request): @@ -1348,6 +1353,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}") diff --git a/tests/test_httpx_batch.py b/tests/test_httpx_batch.py index 9e42d432..3ea8bd38 100644 --- a/tests/test_httpx_batch.py +++ b/tests/test_httpx_batch.py @@ -409,6 +409,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" diff --git a/tests/test_phoenix_channel_exceptions.py b/tests/test_phoenix_channel_exceptions.py index b7f11dcb..507a9580 100644 --- a/tests/test_phoenix_channel_exceptions.py +++ b/tests/test_phoenix_channel_exceptions.py @@ -503,6 +503,7 @@ async def test_phoenix_channel_unsubscribe_error_forcing(server, query_str): query = gql(query_str) with pytest.raises(TransportProtocolError): async with Client(transport=transport) as session: + assert isinstance(session.transport, PhoenixChannelWebsocketsTransport) async for _result in session.subscribe(query): await session.transport._send_stop_message(2) await asyncio.sleep(10 * MS) diff --git a/tests/test_phoenix_channel_subscription.py b/tests/test_phoenix_channel_subscription.py index a54c594c..b26a0b27 100644 --- a/tests/test_phoenix_channel_subscription.py +++ b/tests/test_phoenix_channel_subscription.py @@ -247,6 +247,9 @@ async def testing_stopping_without_break(): subscription = gql(subscription_str.format(count=count)) async with Client(transport=transport) as session: + + assert isinstance(session.transport, PhoenixChannelWebsocketsTransport) + async for result in session.subscribe(subscription): number = result["countdown"]["number"] print(f"Number received: {number}") diff --git a/tests/test_requests.py b/tests/test_requests.py index 7de4a12a..c6cee244 100644 --- a/tests/test_requests.py +++ b/tests/test_requests.py @@ -591,6 +591,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) diff --git a/tests/test_requests_batch.py b/tests/test_requests_batch.py index 93264824..197ffc6a 100644 --- a/tests/test_requests_batch.py +++ b/tests/test_requests_batch.py @@ -575,6 +575,7 @@ def test_code(): execution_results = session.execute_batch(query, get_execution_result=True) + assert execution_results[0].extensions is not None assert execution_results[0].extensions["key1"] == "val1" await run_sync_test(server, test_code)