-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathtesting.py
More file actions
180 lines (155 loc) · 6.63 KB
/
testing.py
File metadata and controls
180 lines (155 loc) · 6.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
from __future__ import annotations
import uuid
from typing import (
TYPE_CHECKING,
Any,
Optional,
Union,
)
from graphql import ExecutionResult, GraphQLError, GraphQLFormattedError
from channels.testing.websocket import WebsocketCommunicator
from graphql_server.subscriptions import (
GRAPHQL_TRANSPORT_WS_PROTOCOL,
GRAPHQL_WS_PROTOCOL,
)
from graphql_server.subscriptions.protocols.graphql_transport_ws import (
types as transport_ws_types,
)
from graphql_server.subscriptions.protocols.graphql_ws import types as ws_types
if TYPE_CHECKING:
from collections.abc import AsyncIterator # pragma: no cover
from types import TracebackType # pragma: no cover
from typing_extensions import Self # pragma: no cover
from asgiref.typing import ASGIApplication # pragma: no cover
class GraphQLWebsocketCommunicator(WebsocketCommunicator):
"""A test communicator for GraphQL over Websockets.
```python
import pytest
from graphql_server.channels.testing import GraphQLWebsocketCommunicator
from myapp.asgi import application
@pytest.fixture
async def gql_communicator():
async with GraphQLWebsocketCommunicator(application, path="/graphql") as client:
yield client
async def test_subscribe_echo(gql_communicator):
async for res in gql_communicator.subscribe(
query='subscription { echo(message: "Hi") }'
):
assert res.data == {"echo": "Hi"}
```
"""
def __init__(
self,
application: ASGIApplication,
path: str,
headers: Optional[list[tuple[bytes, bytes]]] = None,
protocol: str = GRAPHQL_TRANSPORT_WS_PROTOCOL,
connection_params: dict | None = None,
**kwargs: Any,
) -> None:
"""Create a new communicator.
Args:
application: Your asgi application that encapsulates the GraphQL schema.
path: the url endpoint for the schema.
protocol: currently this supports `graphql-transport-ws` only.
connection_params: a dictionary of connection parameters to send to the server.
headers: a list of tuples to be sent as headers to the server.
subprotocols: an ordered list of preferred subprotocols to be sent to the server.
**kwargs: additional arguments to be passed to the `WebsocketCommunicator` constructor.
"""
if connection_params is None: # pragma: no cover - tested via custom initialisation
connection_params = {}
self.protocol = protocol
subprotocols = kwargs.get("subprotocols", [])
subprotocols.append(protocol)
self.connection_params = connection_params
super().__init__(application, path, headers, subprotocols=subprotocols)
async def __aenter__(self) -> Self:
await self.gql_init()
return self
async def __aexit__(
self,
exc_type: Optional[type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> None:
await self.disconnect()
async def gql_init(self) -> None:
res = await self.connect()
if self.protocol == GRAPHQL_TRANSPORT_WS_PROTOCOL:
assert res == (True, GRAPHQL_TRANSPORT_WS_PROTOCOL)
await self.send_json_to(
transport_ws_types.ConnectionInitMessage(
{"type": "connection_init", "payload": self.connection_params}
)
)
transport_ws_connection_ack_message: transport_ws_types.ConnectionAckMessage = await self.receive_json_from()
assert transport_ws_connection_ack_message == {"type": "connection_ack"}
else:
assert res == (True, GRAPHQL_WS_PROTOCOL)
await self.send_json_to(
ws_types.ConnectionInitMessage({"type": "connection_init"})
)
ws_connection_ack_message: ws_types.ConnectionAckMessage = (
await self.receive_json_from()
)
assert ws_connection_ack_message["type"] == "connection_ack"
# Actual `ExecutionResult`` objects are not available client-side, since they
# get transformed into `FormattedExecutionResult` on the wire, but we attempt
# to do a limited representation of them here, to make testing simpler.
async def subscribe(
self, query: str, variables: Optional[dict] = None
) -> Union[ExecutionResult, AsyncIterator[ExecutionResult]]:
id_ = uuid.uuid4().hex
if self.protocol == GRAPHQL_TRANSPORT_WS_PROTOCOL:
await self.send_json_to(
transport_ws_types.SubscribeMessage(
{
"id": id_,
"type": "subscribe",
"payload": {"query": query, "variables": variables},
}
)
)
else:
start_message: ws_types.StartMessage = {
"type": "start",
"id": id_,
"payload": {
"query": query,
},
}
if variables is not None: # pragma: no cover - exercised in higher-level tests
start_message["payload"]["variables"] = variables
await self.send_json_to(start_message)
while True:
message: transport_ws_types.Message = await self.receive_json_from(
timeout=5
)
if message["type"] == "next":
payload = message["payload"]
ret = ExecutionResult(payload.get("data"), None)
if "errors" in payload:
ret.errors = self.process_errors(payload.get("errors") or [])
ret.extensions = payload.get("extensions", None)
yield ret
elif message["type"] == "error": # pragma: no cover - network failures untested
error_payload = message["payload"]
yield ExecutionResult(
data=None, errors=self.process_errors(error_payload)
)
return # an error message is the last message for a subscription
else:
return
def process_errors(self, errors: list[GraphQLFormattedError]) -> list[GraphQLError]:
"""Reconstructs a GraphQLError from a FormattedGraphQLError."""
result = []
for f_error in errors:
error = GraphQLError(
message=f_error["message"],
extensions=f_error.get("extensions", None),
)
error.path = f_error.get("path", None)
result.append(error)
return result
__all__ = ["GraphQLWebsocketCommunicator"]