Skip to content

Commit

Permalink
Simplify testing of aiogqlc based code (#45)
Browse files Browse the repository at this point in the history
  • Loading branch information
DoctorJohn authored Jan 2, 2024
1 parent af176f3 commit de1b76c
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 3 deletions.
9 changes: 7 additions & 2 deletions aiogqlc/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

import aiohttp
import aiohttp.client
import aiohttp.test_utils

from aiogqlc.constants import GRAPHQL_WS
from aiogqlc.errors import (
Expand Down Expand Up @@ -45,7 +46,7 @@ class GraphQLWSManager:
def __init__(
self,
endpoint: str,
session: aiohttp.ClientSession,
session: Union[aiohttp.ClientSession, aiohttp.test_utils.TestClient],
connection_params: Optional[ConnectionInitParams] = None,
) -> None:
self._endpoint = endpoint
Expand Down Expand Up @@ -194,7 +195,11 @@ async def terminate_connection(self) -> None:


class GraphQLClient:
def __init__(self, endpoint: str, session: aiohttp.ClientSession) -> None:
def __init__(
self,
endpoint: str,
session: Union[aiohttp.ClientSession, aiohttp.test_utils.TestClient],
) -> None:
self.endpoint = endpoint
self.session = session

Expand Down
32 changes: 32 additions & 0 deletions docs/testing.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Testing

There is no need to mock `aiogqlc` in your tests.
Instead you might want to mock your GraphQL backend.
This can be done by providing a `aiohttp.web.Application`.

The following example shows a `pytest` and `pytest-aiohttp` based test using a mock GraphQL backend:

```python
import aiohttp
import aiohttp.web
from aiogqlc import GraphQLClient


class TestGraphQLView(aiohttp.web.View):
async def post(self):
return aiohttp.web.json_response({"data": {"ping": "pong"}})


async def test_ping_query(aiohttp_client):
app = aiohttp.web.Application()
app.router.add_route("*", "/graphql", TestGraphQLView)

graphql_session = await aiohttp_client(app)
client = GraphQLClient(endpoint="/graphql", session=graphql_session)

response = await client.execute("query { ping }")
assert await response.json() == {"data": {"ping": "pong"}}
```

In fact, the `aiogqlc` test suite itself is based on this approach.
Take a look at [the aiogqlc tests directory](https://github.com/DoctorJohn/aiogqlc/tree/main/tests) for more advanced examples.
3 changes: 2 additions & 1 deletion mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -35,5 +35,6 @@ nav:
- Authentication: authentication.md
- Advanced Usage: advanced-usage.md
- Guides:
- Contributing: contributing.md
- Testing: testing.md
- Migrating: migrating.md
- Contributing: contributing.md

0 comments on commit de1b76c

Please sign in to comment.