Skip to content

Commit fe1986d

Browse files
authored
Merge pull request #36 from Pelleplutt/master
Add ability to override init_payload for subscriptions.
2 parents 6ab30cf + f80d65e commit fe1986d

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

python_graphql_client/graphql_client.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,9 +82,12 @@ async def subscribe(
8282
variables: dict = None,
8383
operation_name: str = None,
8484
headers: dict = {},
85+
init_payload: dict = {},
8586
):
8687
"""Make asynchronous request for GraphQL subscription."""
87-
connection_init_message = json.dumps({"type": "connection_init", "payload": {}})
88+
connection_init_message = json.dumps(
89+
{"type": "connection_init", "payload": init_payload}
90+
)
8891

8992
request_body = self.__request_body(
9093
query=query, variables=variables, operation_name=operation_name

tests/test_graphql_client.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -323,3 +323,40 @@ async def test_headers_passed_to_websocket_connect(self, mock_connect):
323323
)
324324

325325
mock_handle.assert_has_calls([call({"data": {"messageAdded": "one"}})])
326+
327+
@patch("websockets.connect")
328+
async def test_init_payload_passed_in_init_message(self, mock_connect):
329+
"""Subsribe a GraphQL subscription."""
330+
mock_websocket = mock_connect.return_value.__aenter__.return_value
331+
mock_websocket.send = AsyncMock()
332+
mock_websocket.__aiter__.return_value = [
333+
'{"type": "connection_init", "payload": '
334+
'{"init": "this is the init_payload"}}',
335+
'{"type": "data", "id": "1", "payload": {"data": {"messageAdded": "one"}}}',
336+
]
337+
expected_endpoint = "ws://www.test-api.com/graphql"
338+
client = GraphqlClient(endpoint=expected_endpoint)
339+
340+
query = """
341+
subscription onMessageAdded {
342+
messageAdded
343+
}
344+
"""
345+
init_payload = '{"init": "this is the init_payload"}'
346+
347+
mock_handle = MagicMock()
348+
349+
await client.subscribe(
350+
query=query, handle=mock_handle, init_payload=init_payload
351+
)
352+
353+
mock_connect.assert_called_with(
354+
expected_endpoint, subprotocols=["graphql-ws"], extra_headers={}
355+
)
356+
357+
mock_handle.assert_has_calls(
358+
[
359+
call({"init": "this is the init_payload"}),
360+
call({"data": {"messageAdded": "one"}}),
361+
]
362+
)

0 commit comments

Comments
 (0)