forked from datadvance/DjangoChannelsGraphqlWs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_basic.py
516 lines (415 loc) · 16.4 KB
/
test_basic.py
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
# Copyright (C) DATADVANCE, 2010-2021
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""Check different basic scenarios."""
# NOTE: The GraphQL schema is defined at the end of the file.
# NOTE: In this file we use `strict_ordering=True` to simplify testing.
import json
import textwrap
import uuid
import graphene
import pytest
import channels_graphql_ws
@pytest.mark.asyncio
async def test_main_usecase(gql):
"""Test main use-case with the GraphQL over WebSocket."""
print("Establish & initialize WebSocket GraphQL connection.")
client = gql(
query=Query,
mutation=Mutation,
subscription=Subscription,
consumer_attrs={"strict_ordering": True},
)
await client.connect_and_init()
print("Make simple GraphQL query and check the response.")
msg_id = await client.send(
msg_type="start",
payload={
"query": "query op_name { value }",
"variables": {},
"operationName": "op_name",
},
)
resp = await client.receive(assert_id=msg_id, assert_type="data")
assert resp["data"]["value"] == Query.VALUE
await client.receive(assert_id=msg_id, assert_type="complete")
print("Subscribe to GraphQL subscription.")
sub_id = await client.send(
msg_type="start",
payload={
"query": textwrap.dedent(
"""
subscription op_name {
on_chat_message_sent(user_id: ALICE) { event }
}
"""
),
"variables": {},
"operationName": "op_name",
},
)
await client.assert_no_messages()
print("Trigger the subscription by mutation to receive notification.")
message = f"Hi! {str(uuid.uuid4().hex)}"
msg_id = await client.send(
msg_type="start",
payload={
"query": textwrap.dedent(
"""
mutation op_name($message: String!) {
send_chat_message(message: $message) {
message
}
}
"""
),
"variables": {"message": message},
"operationName": "op_name",
},
)
# Mutation response.
resp = await client.receive(assert_id=msg_id, assert_type="data")
assert resp["data"] == {"send_chat_message": {"message": message}}
await client.receive(assert_id=msg_id, assert_type="complete")
# Subscription notification.
resp = await client.receive(assert_id=sub_id, assert_type="data")
event = resp["data"]["on_chat_message_sent"]["event"]
assert json.loads(event) == {
"user_id": UserId.ALICE,
"payload": message,
}, "Subscription notification contains wrong data!"
print("Disconnect and wait the application to finish gracefully.")
await client.finalize()
@pytest.mark.asyncio
async def test_subscribe_unsubscribe(gql):
"""Test subscribe-unsubscribe behavior with the GraphQL over WebSocket.
0. Subscribe to GraphQL subscription: messages for Alice.
1. Send STOP message and unsubscribe.
2. Subscribe to GraphQL subscription: messages for Tom.
3. Call unsubscribe method of the Subscription instance
(via `kick_out_user` mutation).
4. Execute some mutation.
5. Check subscription notifications: there are no notifications.
"""
print("Establish & initialize WebSocket GraphQL connection.")
client = gql(
query=Query,
mutation=Mutation,
subscription=Subscription,
consumer_attrs={"strict_ordering": True},
)
await client.connect_and_init()
print("Subscribe to GraphQL subscription.")
sub_id = await client.send(
msg_type="start",
payload={
"query": textwrap.dedent(
"""
subscription op_name { on_chat_message_sent(user_id: ALICE) { event } }
"""
),
"variables": {},
"operationName": "op_name",
},
)
print("Stop subscription by id.")
await client.send(msg_id=sub_id, msg_type="stop")
await client.receive(assert_id=sub_id, assert_type="complete")
print("Subscribe to GraphQL subscription.")
sub_id = await client.send(
msg_type="start",
payload={
"query": textwrap.dedent(
"""
subscription op_name {
on_chat_message_sent(user_id: TOM) { event }
}
"""
),
"variables": {},
"operationName": "op_name",
},
)
print("Stop all subscriptions for TOM.")
msg_id = await client.send(
msg_type="start",
payload={
"query": "mutation op_name { kick_out_user(user_id: TOM) { success } }",
"variables": {},
"operationName": "op_name",
},
)
# Mutation & unsubscription responses.
await client.receive(assert_id=msg_id, assert_type="data")
await client.receive(assert_id=msg_id, assert_type="complete")
await client.receive(assert_id=sub_id, assert_type="complete")
print("Trigger the subscription by mutation to receive notification.")
msg_id = await client.send(
msg_type="start",
payload={
"query": textwrap.dedent(
"""
mutation op_name {
send_chat_message(message: "Is there anybody here?") {
message
}
}
"""
),
"variables": "",
"operationName": "op_name",
},
)
# Mutation response.
await client.receive(assert_id=msg_id, assert_type="data")
await client.receive(assert_id=msg_id, assert_type="complete")
# Check notifications: there are no notifications! Previously,
# we have unsubscribed from all subscriptions.
await client.assert_no_messages(
"Notification received in spite of we have unsubscribed from all subscriptions!"
)
print("Disconnect and wait the application to finish gracefully.")
await client.finalize()
@pytest.mark.asyncio
async def test_subscription_groups(gql):
"""Test notifications behavior with different subscription group.
Test notifications and subscriptions behavior depending on the
different subscription groups.
0. Subscribe to the group1: messages for Alice.
1. Subscribe to the group2: messages for Tom.
2. Trigger group1 (send message to Alice) and check subscribed
recipients: Alice.
3. Trigger group2 (send message to Tom) and check subscribed
recipients: Tom.
4. Trigger all groups (send messages for all users) and check
subscribed recipients: Alice, Tom.
"""
async def create_and_subscribe(user_id):
"""Establish and initialize WebSocket GraphQL connection.
Subscribe to GraphQL subscription by user_id.
Args:
user_id: User ID for `on_chat_message_sent` subscription.
Returns:
sub_id: Subscription uid.
client: Client, instance of the `WebsocketCommunicator`.
"""
client = gql(
query=Query,
mutation=Mutation,
subscription=Subscription,
consumer_attrs={"strict_ordering": True, "confirm_subscriptions": True},
)
await client.connect_and_init()
sub_id = await client.send(
msg_type="start",
payload={
"query": textwrap.dedent(
"""
subscription op_name($user_id: UserId) {
on_chat_message_sent(user_id: $user_id) { event }
}
"""
),
"variables": {"user_id": user_id},
"operationName": "op_name",
},
)
# Receive the subscription confirmation message.
resp = await client.receive(assert_id=sub_id, assert_type="data")
assert resp == {"data": None}
return sub_id, client
async def trigger_subscription(client, user_id, message):
"""Send a message to user using `send_chat_message` mutation.
Args:
client: Client, instance of WebsocketCommunicator.
user_id: User ID for `send_chat_message` mutation.
message: Any string message.
"""
msg_id = await client.send(
msg_type="start",
payload={
"query": textwrap.dedent(
"""
mutation op_name($message: String!, $user_id: UserId) {
send_chat_message(message: $message, user_id: $user_id) {
message
}
}
"""
),
"variables": {"message": message, "user_id": user_id},
"operationName": "op_name",
},
)
# Mutation response.
await client.receive(assert_id=msg_id, assert_type="data")
await client.receive(assert_id=msg_id, assert_type="complete")
def check_resp(resp, user_id, message):
"""Check the response from `on_chat_message_sent` subscription.
Args:
user_id: Expected user ID.
message: Expected message string.
"""
event = resp["data"]["on_chat_message_sent"]["event"]
assert json.loads(event) == {
"user_id": user_id,
"payload": message,
}, "Subscription notification contains wrong data!"
print("Initialize the connection, create subscriptions.")
alice_id = "ALICE"
tom_id = "TOM"
# Subscribe to messages for Alice.
uid_alice, comm_alice = await create_and_subscribe(alice_id)
# Subscribe to messages for TOM.
uid_tom, comm_tom = await create_and_subscribe(tom_id)
print("Trigger subscription: send message to Tom.")
message = "Hi, Tom!"
await trigger_subscription(comm_alice, tom_id, message)
# Check Tom's notifications.
resp = await comm_tom.receive(assert_id=uid_tom, assert_type="data")
check_resp(resp, UserId[tom_id].value, message)
# Any other did not receive any notifications.
await comm_alice.assert_no_messages()
print("Trigger subscription: send message to Alice.")
message = "Hi, Alice!"
await trigger_subscription(comm_tom, alice_id, message)
# Check Alice's notifications.
resp = await comm_alice.receive(assert_id=uid_alice, assert_type="data")
check_resp(resp, UserId[alice_id].value, message)
# Any other did not receive any notifications.
await comm_tom.assert_no_messages()
print("Trigger subscription: send message to all groups.")
message = "test... ping..."
await trigger_subscription(comm_tom, None, message)
print("Check Tom's and Alice's notifications.")
resp = await comm_tom.receive(assert_id=uid_tom, assert_type="data")
check_resp(resp, UserId[tom_id].value, message)
resp = await comm_alice.receive(assert_id=uid_alice, assert_type="data")
check_resp(resp, UserId[alice_id].value, message)
print("Disconnect and wait the application to finish gracefully.")
await comm_tom.finalize()
await comm_alice.finalize()
@pytest.mark.asyncio
async def test_keepalive(gql):
"""Test that server sends keepalive messages."""
print("Establish & initialize WebSocket GraphQL connection.")
client = gql(
query=Query,
mutation=Mutation,
subscription=Subscription,
consumer_attrs={"strict_ordering": True, "send_keepalive_every": 0.05},
)
await client.connect_and_init()
async def receive_keep_alive():
response = await client.transport.receive()
assert response["type"] == "ka", "Non keep alive response received!"
await receive_keep_alive()
print("Receive several keepalive messages.")
for _ in range(3):
await receive_keep_alive()
print("Send connection termination message.")
await client.send(msg_id=None, msg_type="connection_terminate")
print("Disconnect and wait the application to finish gracefully.")
await client.finalize()
# ---------------------------------------------------------------------- GRAPHQL BACKEND
class UserId(graphene.Enum):
"""User IDs for sending messages."""
TOM = 0
ALICE = 1
class OnChatMessageSent(channels_graphql_ws.Subscription):
"""Test GraphQL subscription.
Subscribe to receive messages by user ID.
"""
# pylint: disable=arguments-differ
event = graphene.JSONString()
class Arguments:
"""That is how subscription arguments are defined."""
user_id = UserId()
def subscribe(self, info, user_id=None):
"""Specify subscription groups when client subscribes."""
del info
assert self is None, "Root `self` expected to be `None`!"
# Subscribe to the group corresponding to the user.
if not user_id is None:
return [f"user_{user_id}"]
# Subscribe to default group.
return []
def publish(self, info, user_id):
"""Publish query result to the subscribers."""
del info
event = {"user_id": user_id, "payload": self}
return OnChatMessageSent(event=event)
@classmethod
def notify(cls, user_id, message):
"""Example of the `notify` classmethod usage."""
# Find the subscription group for user.
group = None if user_id is None else f"user_{user_id}"
cls.broadcast(group=group, payload=message)
class SendChatMessage(graphene.Mutation):
"""Test GraphQL mutation.
Send message to the user or all users.
"""
class Output(graphene.ObjectType):
"""Mutation result."""
message = graphene.String()
user_id = UserId()
class Arguments:
"""That is how mutation arguments are defined."""
message = graphene.String(required=True)
user_id = graphene.Argument(UserId, required=False)
def mutate(self, info, message, user_id=None):
"""Send message to the user or all users."""
del info
assert self is None, "Root `self` expected to be `None`!"
# Notify subscribers.
OnChatMessageSent.notify(message=message, user_id=user_id)
return SendChatMessage.Output(message=message, user_id=user_id)
class KickOutUser(graphene.Mutation):
"""Test GraphQL mutation.
Stop all subscriptions associated with the user.
"""
class Arguments:
"""That is how mutation arguments are defined."""
user_id = UserId()
success = graphene.Boolean()
def mutate(self, info, user_id):
"""Unsubscribe everyone associated with the user_id."""
del info
assert self is None, "Root `self` expected to be `None`!"
OnChatMessageSent.unsubscribe(group=f"user_{user_id}")
return KickOutUser(success=True)
class Subscription(graphene.ObjectType):
"""GraphQL subscriptions."""
on_chat_message_sent = OnChatMessageSent.Field()
class Mutation(graphene.ObjectType):
"""GraphQL mutations."""
send_chat_message = SendChatMessage.Field()
kick_out_user = KickOutUser.Field()
class Query(graphene.ObjectType):
"""Root GraphQL query."""
VALUE = str(uuid.uuid4().hex)
value = graphene.String(args={"issue_error": graphene.Boolean(default_value=False)})
def resolve_value(self, info, issue_error):
"""Resolver to return predefined value which can be tested."""
del info
assert self is None, "Root `self` expected to be `None`!"
if issue_error:
raise RuntimeError(Query.VALUE)
return Query.VALUE