-
-
Notifications
You must be signed in to change notification settings - Fork 565
/
Copy pathtest_graphql_transport_ws.py
1116 lines (895 loc) · 34.1 KB
/
test_graphql_transport_ws.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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import asyncio
import contextlib
import json
import time
from collections.abc import AsyncGenerator
from datetime import timedelta
from typing import TYPE_CHECKING, Optional, Union
from unittest.mock import AsyncMock, Mock, patch
import pytest
import pytest_asyncio
from pytest_mock import MockerFixture
from strawberry.subscriptions import GRAPHQL_TRANSPORT_WS_PROTOCOL
from strawberry.subscriptions.protocols.graphql_transport_ws.types import (
CompleteMessage,
ConnectionAckMessage,
ConnectionInitMessage,
ErrorMessage,
NextMessage,
PingMessage,
PongMessage,
SubscribeMessage,
)
from tests.http.clients.base import DebuggableGraphQLTransportWSHandler
from tests.views.schema import MyExtension, Schema, Subscription
if TYPE_CHECKING:
from tests.http.clients.base import HttpClient, WebSocketClient
@pytest_asyncio.fixture
async def ws_raw(http_client: HttpClient) -> AsyncGenerator[WebSocketClient, None]:
async with http_client.ws_connect(
"/graphql", protocols=[GRAPHQL_TRANSPORT_WS_PROTOCOL]
) as ws:
yield ws
await ws.close()
assert ws.closed
@pytest_asyncio.fixture
async def ws(ws_raw: WebSocketClient) -> WebSocketClient:
await ws_raw.send_message({"type": "connection_init"})
connection_ack_message: ConnectionAckMessage = await ws_raw.receive_json()
assert connection_ack_message == {"type": "connection_ack"}
return ws_raw
def assert_next(
next_message: NextMessage,
id: str,
data: dict[str, object],
extensions: Optional[dict[str, object]] = None,
):
"""
Assert that the NextMessage payload contains the provided data.
If extensions is provided, it will also assert that the
extensions are present
"""
assert next_message["type"] == "next"
assert next_message["id"] == id
assert set(next_message["payload"].keys()) <= {"data", "errors", "extensions"}
assert "data" in next_message["payload"]
assert next_message["payload"]["data"] == data
if extensions is not None:
assert "extensions" in next_message["payload"]
assert next_message["payload"]["extensions"] == extensions
async def test_unknown_message_type(ws_raw: WebSocketClient):
ws = ws_raw
await ws.send_json({"type": "NOT_A_MESSAGE_TYPE"})
await ws.receive(timeout=2)
assert ws.closed
assert ws.close_code == 4400
assert ws.close_reason == "Unknown message type: NOT_A_MESSAGE_TYPE"
async def test_missing_message_type(ws_raw: WebSocketClient):
ws = ws_raw
await ws.send_json({"notType": None})
await ws.receive(timeout=2)
assert ws.closed
assert ws.close_code == 4400
assert ws.close_reason == "Failed to parse message"
async def test_parsing_an_invalid_message(ws: WebSocketClient):
await ws.send_json({"type": "subscribe", "notPayload": None})
await ws.receive(timeout=2)
assert ws.closed
assert ws.close_code == 4400
assert ws.close_reason == "Failed to parse message"
async def test_non_text_ws_messages_result_in_socket_closure(ws_raw: WebSocketClient):
ws = ws_raw
await ws.send_bytes(
json.dumps(ConnectionInitMessage({"type": "connection_init"})).encode()
)
await ws.receive(timeout=2)
assert ws.closed
assert ws.close_code == 4400
assert ws.close_reason == "WebSocket message type must be text"
async def test_non_json_ws_messages_result_in_socket_closure(ws_raw: WebSocketClient):
ws = ws_raw
await ws.send_text("not valid json")
await ws.receive(timeout=2)
assert ws.closed
assert ws.close_code == 4400
assert ws.close_reason == "WebSocket message must be valid JSON"
async def test_ws_message_frame_types_cannot_be_mixed(ws_raw: WebSocketClient):
ws = ws_raw
await ws.send_message({"type": "connection_init"})
ack_message: ConnectionAckMessage = await ws.receive_json()
assert ack_message == {"type": "connection_ack"}
await ws.send_bytes(
json.dumps(
SubscribeMessage(
{
"id": "sub1",
"type": "subscribe",
"payload": {
"query": "subscription { debug { isConnectionInitTimeoutTaskDone } }"
},
}
)
).encode()
)
await ws.receive(timeout=2)
assert ws.closed
assert ws.close_code == 4400
assert ws.close_reason == "WebSocket message type must be text"
async def test_connection_init_timeout(
request: object, http_client_class: type[HttpClient]
):
with contextlib.suppress(ImportError):
from tests.http.clients.aiohttp import AioHttpClient
if http_client_class == AioHttpClient:
pytest.skip(
"Closing a AIOHTTP WebSocket from a "
"task currently doesn't work as expected"
)
test_client = http_client_class()
test_client.create_app(connection_init_wait_timeout=timedelta(seconds=0))
async with test_client.ws_connect(
"/graphql", protocols=[GRAPHQL_TRANSPORT_WS_PROTOCOL]
) as ws:
await ws.receive(timeout=2)
assert ws.closed
assert ws.close_code == 4408
assert ws.close_reason == "Connection initialisation timeout"
@pytest.mark.flaky
async def test_connection_init_timeout_cancellation(
ws_raw: WebSocketClient,
):
# Verify that the timeout task is cancelled after the connection Init
# message is received
ws = ws_raw
await ws.send_message({"type": "connection_init"})
connection_ack_message: ConnectionAckMessage = await ws.receive_json()
assert connection_ack_message == {"type": "connection_ack"}
await ws.send_message(
{
"id": "sub1",
"type": "subscribe",
"payload": {
"query": "subscription { debug { isConnectionInitTimeoutTaskDone } }"
},
}
)
next_message: NextMessage = await ws.receive_json()
assert_next(
next_message, "sub1", {"debug": {"isConnectionInitTimeoutTaskDone": True}}
)
@pytest.mark.xfail(reason="This test is flaky")
async def test_close_twice(
mocker: MockerFixture, request: object, http_client_class: type[HttpClient]
):
test_client = http_client_class()
test_client.create_app(connection_init_wait_timeout=timedelta(seconds=0.25))
async with test_client.ws_connect(
"/graphql", protocols=[GRAPHQL_TRANSPORT_WS_PROTOCOL]
) as ws:
transport_close = mocker.patch.object(ws, "close")
# We set payload is set to "invalid value" to force a invalid payload error
# which will close the connection
await ws.send_json({"type": "connection_init", "payload": "invalid value"})
# Yield control so that ._close can be called
await asyncio.sleep(0)
for t in asyncio.all_tasks():
if (
t.get_coro().__qualname__
== "BaseGraphQLTransportWSHandler.handle_connection_init_timeout"
):
# The init timeout task should be cancelled
with pytest.raises(asyncio.CancelledError):
await t
await ws.receive(timeout=0.5)
assert ws.closed
assert ws.close_code == 4400
assert ws.close_reason == "Invalid connection init payload"
transport_close.assert_not_called()
async def test_too_many_initialisation_requests(ws: WebSocketClient):
await ws.send_message({"type": "connection_init"})
await ws.receive(timeout=2)
assert ws.closed
assert ws.close_code == 4429
assert ws.close_reason == "Too many initialisation requests"
async def test_connections_are_accepted_by_default(ws_raw: WebSocketClient):
await ws_raw.send_message({"type": "connection_init"})
connection_ack_message: ConnectionAckMessage = await ws_raw.receive_json()
assert connection_ack_message == {"type": "connection_ack"}
await ws_raw.close()
assert ws_raw.closed
@pytest.mark.parametrize("payload", [None, {"token": "secret"}])
async def test_setting_a_connection_ack_payload(ws_raw: WebSocketClient, payload):
await ws_raw.send_message(
{
"type": "connection_init",
"payload": {"test-accept": True, "ack-payload": payload},
}
)
connection_ack_message: ConnectionAckMessage = await ws_raw.receive_json()
assert connection_ack_message == {"type": "connection_ack", "payload": payload}
await ws_raw.close()
assert ws_raw.closed
async def test_connection_ack_payload_may_be_unset(ws_raw: WebSocketClient):
await ws_raw.send_message(
{
"type": "connection_init",
"payload": {"test-accept": True},
}
)
connection_ack_message: ConnectionAckMessage = await ws_raw.receive_json()
assert connection_ack_message == {"type": "connection_ack"}
await ws_raw.close()
assert ws_raw.closed
async def test_rejecting_connection_closes_socket_with_expected_code_and_message(
ws_raw: WebSocketClient,
):
await ws_raw.send_message(
{"type": "connection_init", "payload": {"test-reject": True}}
)
await ws_raw.receive(timeout=2)
assert ws_raw.closed
assert ws_raw.close_code == 4403
assert ws_raw.close_reason == "Forbidden"
async def test_context_can_be_modified_from_within_on_ws_connect(
ws_raw: WebSocketClient,
):
await ws_raw.send_message(
{
"type": "connection_init",
"payload": {"test-modify": True},
}
)
connection_ack_message: ConnectionAckMessage = await ws_raw.receive_json()
assert connection_ack_message == {"type": "connection_ack"}
await ws_raw.send_message(
{
"type": "subscribe",
"id": "demo",
"payload": {
"query": "subscription { connectionParams }",
},
}
)
next_message: NextMessage = await ws_raw.receive_json()
assert next_message["type"] == "next"
assert next_message["id"] == "demo"
assert "data" in next_message["payload"]
assert next_message["payload"]["data"] == {
"connectionParams": {"test-modify": True, "modified": True}
}
await ws_raw.close()
assert ws_raw.closed
async def test_ping_pong(ws: WebSocketClient):
await ws.send_message({"type": "ping"})
pong_message: PongMessage = await ws.receive_json()
assert pong_message == {"type": "pong"}
async def test_can_send_payload_with_additional_things(ws_raw: WebSocketClient):
ws = ws_raw
# send init
await ws.send_message({"type": "connection_init"})
await ws.receive(timeout=2)
await ws.send_message(
{
"type": "subscribe",
"payload": {
"query": 'subscription { echo(message: "Hi") }',
"extensions": {
"some": "other thing",
},
},
"id": "1",
}
)
next_message: NextMessage = await ws.receive_json(timeout=2)
assert next_message == {
"type": "next",
"id": "1",
"payload": {"data": {"echo": "Hi"}, "extensions": {"example": "example"}},
}
async def test_server_sent_ping(ws: WebSocketClient):
await ws.send_message(
{
"id": "sub1",
"type": "subscribe",
"payload": {"query": "subscription { requestPing }"},
}
)
ping_message: PingMessage = await ws.receive_json()
assert ping_message == {"type": "ping"}
await ws.send_message({"type": "pong"})
next_message: NextMessage = await ws.receive_json()
assert_next(next_message, "sub1", {"requestPing": True})
complete_message: CompleteMessage = await ws.receive_json()
assert complete_message == {"id": "sub1", "type": "complete"}
async def test_unauthorized_subscriptions(ws_raw: WebSocketClient):
ws = ws_raw
await ws.send_message(
{
"id": "sub1",
"type": "subscribe",
"payload": {"query": 'subscription { echo(message: "Hi") }'},
}
)
await ws.receive(timeout=2)
assert ws.closed
assert ws.close_code == 4401
assert ws.close_reason == "Unauthorized"
async def test_duplicated_operation_ids(ws: WebSocketClient):
await ws.send_message(
{
"id": "sub1",
"type": "subscribe",
"payload": {"query": 'subscription { echo(message: "Hi", delay: 5) }'},
}
)
await ws.send_message(
{
"id": "sub1",
"type": "subscribe",
"payload": {"query": 'subscription { echo(message: "Hi", delay: 5) }'},
}
)
await ws.receive(timeout=2)
assert ws.closed
assert ws.close_code == 4409
assert ws.close_reason == "Subscriber for sub1 already exists"
async def test_reused_operation_ids(ws: WebSocketClient):
"""Test that an operation id can be re-used after it has been
previously used for a completed operation.
"""
# Use sub1 as an id for an operation
await ws.send_message(
{
"id": "sub1",
"type": "subscribe",
"payload": {"query": 'subscription { echo(message: "Hi") }'},
}
)
next_message1: NextMessage = await ws.receive_json()
assert_next(next_message1, "sub1", {"echo": "Hi"})
complete_message: CompleteMessage = await ws.receive_json()
assert complete_message == {"id": "sub1", "type": "complete"}
# operation is now complete. Create a new operation using
# the same ID
await ws.send_message(
{
"id": "sub1",
"type": "subscribe",
"payload": {"query": 'subscription { echo(message: "Hi") }'},
}
)
next_message2: NextMessage = await ws.receive_json()
assert_next(next_message2, "sub1", {"echo": "Hi"})
async def test_simple_subscription(ws: WebSocketClient):
await ws.send_message(
{
"id": "sub1",
"type": "subscribe",
"payload": {"query": 'subscription { echo(message: "Hi") }'},
}
)
next_message: NextMessage = await ws.receive_json()
assert_next(next_message, "sub1", {"echo": "Hi"})
await ws.send_message({"id": "sub1", "type": "complete"})
async def test_subscription_syntax_error(ws: WebSocketClient):
await ws.send_message(
{
"id": "sub1",
"type": "subscribe",
"payload": {"query": "subscription { INVALID_SYNTAX "},
}
)
await ws.receive(timeout=2)
assert ws.closed
assert ws.close_code == 4400
assert ws.close_reason == "Syntax Error: Expected Name, found <EOF>."
async def test_subscription_field_errors(ws: WebSocketClient):
process_errors = Mock()
with patch.object(Schema, "process_errors", process_errors):
await ws.send_message(
{
"id": "sub1",
"type": "subscribe",
"payload": {
"query": "subscription { notASubscriptionField }",
},
}
)
error_message: ErrorMessage = await ws.receive_json()
assert error_message["type"] == "error"
assert error_message["id"] == "sub1"
assert len(error_message["payload"]) == 1
assert "locations" in error_message["payload"][0]
assert error_message["payload"][0]["locations"] == [{"line": 1, "column": 16}]
assert "message" in error_message["payload"][0]
assert (
error_message["payload"][0]["message"]
== "Cannot query field 'notASubscriptionField' on type 'Subscription'."
)
process_errors.assert_called_once()
async def test_subscription_cancellation(ws: WebSocketClient):
await ws.send_message(
{
"id": "sub1",
"type": "subscribe",
"payload": {"query": 'subscription { echo(message: "Hi", delay: 99) }'},
}
)
await ws.send_message(
{
"id": "sub2",
"type": "subscribe",
"payload": {
"query": "subscription { debug { numActiveResultHandlers } }",
},
}
)
next_message: NextMessage = await ws.receive_json()
assert_next(next_message, "sub2", {"debug": {"numActiveResultHandlers": 2}})
complete_message: CompleteMessage = await ws.receive_json()
assert complete_message == {"id": "sub2", "type": "complete"}
await ws.send_message({"id": "sub1", "type": "complete"})
await ws.send_message(
{
"id": "sub3",
"type": "subscribe",
"payload": {
"query": "subscription { debug { numActiveResultHandlers } }",
},
}
)
next_message: NextMessage = await ws.receive_json()
assert_next(next_message, "sub3", {"debug": {"numActiveResultHandlers": 1}})
complete_message: CompleteMessage = await ws.receive_json()
assert complete_message == {"id": "sub3", "type": "complete"}
async def test_subscription_errors(ws: WebSocketClient):
await ws.send_message(
{
"id": "sub1",
"type": "subscribe",
"payload": {
"query": 'subscription { error(message: "TEST ERR") }',
},
}
)
next_message: NextMessage = await ws.receive_json()
assert next_message["type"] == "next"
assert next_message["id"] == "sub1"
assert "errors" in next_message["payload"]
payload_errors = next_message["payload"]["errors"]
assert payload_errors is not None
assert len(payload_errors) == 1
assert "path" in payload_errors[0]
assert payload_errors[0]["path"] == ["error"]
assert "message" in payload_errors[0]
assert payload_errors[0]["message"] == "TEST ERR"
async def test_operation_error_no_complete(ws: WebSocketClient):
"""Test that an "error" message is not followed by "complete"."""
# Since we don't include the operation variables,
# the subscription will fail immediately.
# see https://github.com/enisdenjo/graphql-ws/blob/master/PROTOCOL.md#error
await ws.send_message(
{
"id": "sub1",
"type": "subscribe",
"payload": {
"query": "subscription Foo($bar: String!){ exception(message: $bar) }",
},
}
)
error_message: ErrorMessage = await ws.receive_json()
assert error_message["type"] == "error"
assert error_message["id"] == "sub1"
# after an "error" message, there should be nothing more
# sent regarding "sub1", not even a "complete".
await ws.send_message({"type": "ping"})
pong_message: PongMessage = await ws.receive_json(timeout=1)
assert pong_message == {"type": "pong"}
async def test_subscription_exceptions(ws: WebSocketClient):
process_errors = Mock()
with patch.object(Schema, "process_errors", process_errors):
await ws.send_message(
{
"id": "sub1",
"type": "subscribe",
"payload": {
"query": 'subscription { exception(message: "TEST EXC") }',
},
}
)
next_message: NextMessage = await ws.receive_json()
assert next_message["type"] == "next"
assert next_message["id"] == "sub1"
assert "errors" in next_message["payload"]
assert next_message["payload"]["errors"] == [{"message": "TEST EXC"}]
process_errors.assert_called_once()
async def test_single_result_query_operation(ws: WebSocketClient):
await ws.send_message(
{
"id": "sub1",
"type": "subscribe",
"payload": {"query": "query { hello }"},
}
)
next_message: NextMessage = await ws.receive_json()
assert_next(next_message, "sub1", {"hello": "Hello world"})
complete_message: CompleteMessage = await ws.receive_json()
assert complete_message == {"id": "sub1", "type": "complete"}
async def test_single_result_query_operation_async(ws: WebSocketClient):
"""Test a single result query operation on an
`async` method in the schema, including an artificial
async delay.
"""
await ws.send_message(
{
"id": "sub1",
"type": "subscribe",
"payload": {"query": 'query { asyncHello(name: "Dolly", delay:0.01)}'},
}
)
next_message: NextMessage = await ws.receive_json()
assert_next(next_message, "sub1", {"asyncHello": "Hello Dolly"})
complete_message: CompleteMessage = await ws.receive_json()
assert complete_message == {"id": "sub1", "type": "complete"}
async def test_single_result_query_operation_overlapped(ws: WebSocketClient):
"""Test that two single result queries can be in flight at the same time,
just like regular queries. Start two queries with separate ids. The
first query has a delay, so we expect the message to the second
query to be delivered first.
"""
# first query
await ws.send_message(
{
"id": "sub1",
"type": "subscribe",
"payload": {"query": 'query { asyncHello(name: "Dolly", delay:1)}'},
}
)
# second query
await ws.send_message(
{
"id": "sub2",
"type": "subscribe",
"payload": {"query": 'query { asyncHello(name: "Dolly", delay:0)}'},
}
)
# we expect the message to the second query to arrive first
next_message: NextMessage = await ws.receive_json()
assert_next(next_message, "sub2", {"asyncHello": "Hello Dolly"})
complete_message: CompleteMessage = await ws.receive_json()
assert complete_message == {"id": "sub2", "type": "complete"}
async def test_single_result_mutation_operation(ws: WebSocketClient):
await ws.send_message(
{
"id": "sub1",
"type": "subscribe",
"payload": {"query": "mutation { hello }"},
}
)
next_message: NextMessage = await ws.receive_json()
assert_next(next_message, "sub1", {"hello": "strawberry"})
complete_message: CompleteMessage = await ws.receive_json()
assert complete_message == {"id": "sub1", "type": "complete"}
async def test_single_result_operation_selection(ws: WebSocketClient):
query = """
query Query1 {
hello
}
query Query2 {
hello(name: "Strawberry")
}
"""
await ws.send_message(
{
"id": "sub1",
"type": "subscribe",
"payload": {"query": query, "operationName": "Query2"},
}
)
next_message: NextMessage = await ws.receive_json()
assert_next(next_message, "sub1", {"hello": "Hello Strawberry"})
complete_message: CompleteMessage = await ws.receive_json()
assert complete_message == {"id": "sub1", "type": "complete"}
async def test_single_result_invalid_operation_selection(ws: WebSocketClient):
query = """
query Query1 {
hello
}
"""
await ws.send_message(
{
"id": "sub1",
"type": "subscribe",
"payload": {"query": query, "operationName": "Query2"},
}
)
await ws.receive(timeout=2)
assert ws.closed
assert ws.close_code == 4400
assert ws.close_reason == "Can't get GraphQL operation type"
async def test_single_result_execution_error(ws: WebSocketClient):
process_errors = Mock()
with patch.object(Schema, "process_errors", process_errors):
await ws.send_message(
{
"id": "sub1",
"type": "subscribe",
"payload": {
"query": "query { alwaysFail }",
},
}
)
next_message: NextMessage = await ws.receive_json()
assert next_message["type"] == "next"
assert next_message["id"] == "sub1"
assert "errors" in next_message["payload"]
payload_errors = next_message["payload"]["errors"]
assert payload_errors is not None
assert len(payload_errors) == 1
assert "path" in payload_errors[0]
assert payload_errors[0]["path"] == ["alwaysFail"]
assert "message" in payload_errors[0]
assert payload_errors[0]["message"] == "You are not authorized"
process_errors.assert_called_once()
async def test_single_result_pre_execution_error(ws: WebSocketClient):
"""Test that single-result-operations which raise exceptions
behave in the same way as streaming operations.
"""
process_errors = Mock()
with patch.object(Schema, "process_errors", process_errors):
await ws.send_message(
{
"id": "sub1",
"type": "subscribe",
"payload": {
"query": "query { IDontExist }",
},
}
)
error_message: ErrorMessage = await ws.receive_json()
assert error_message["type"] == "error"
assert error_message["id"] == "sub1"
assert len(error_message["payload"]) == 1
assert "message" in error_message["payload"][0]
assert (
error_message["payload"][0]["message"]
== "Cannot query field 'IDontExist' on type 'Query'."
)
process_errors.assert_called_once()
async def test_single_result_duplicate_ids_sub(ws: WebSocketClient):
"""Test that single-result-operations and streaming operations
share the same ID namespace. Start a regular subscription,
then issue a single-result operation with same ID and expect an
error due to already existing ID
"""
# regular subscription
await ws.send_message(
{
"id": "sub1",
"type": "subscribe",
"payload": {"query": 'subscription { echo(message: "Hi", delay: 5) }'},
}
)
# single result subscription with duplicate id
await ws.send_message(
{
"id": "sub1",
"type": "subscribe",
"payload": {
"query": "query { hello }",
},
}
)
await ws.receive(timeout=2)
assert ws.closed
assert ws.close_code == 4409
assert ws.close_reason == "Subscriber for sub1 already exists"
async def test_single_result_duplicate_ids_query(ws: WebSocketClient):
"""Test that single-result-operations don't allow duplicate
IDs for two asynchronous queries. Issue one async query
with delay, then another with same id. Expect error.
"""
# single result subscription 1
await ws.send_message(
{
"id": "sub1",
"type": "subscribe",
"payload": {"query": 'query { asyncHello(name: "Hi", delay: 5) }'},
}
)
# single result subscription with duplicate id
await ws.send_message(
{
"id": "sub1",
"type": "subscribe",
"payload": {
"query": "query { hello }",
},
}
)
# We expect the remote to close the socket due to duplicate ID in use
await ws.receive(timeout=2)
assert ws.closed
assert ws.close_code == 4409
assert ws.close_reason == "Subscriber for sub1 already exists"
async def test_injects_connection_params(ws_raw: WebSocketClient):
ws = ws_raw
await ws.send_message(
{"type": "connection_init", "payload": {"strawberry": "rocks"}}
)
connection_ack_message: ConnectionAckMessage = await ws.receive_json()
assert connection_ack_message == {"type": "connection_ack"}
await ws.send_message(
{
"id": "sub1",
"type": "subscribe",
"payload": {"query": "subscription { connectionParams }"},
}
)
next_message: NextMessage = await ws.receive_json()
assert_next(next_message, "sub1", {"connectionParams": {"strawberry": "rocks"}})
await ws.send_message({"id": "sub1", "type": "complete"})
async def test_rejects_connection_params_not_dict(ws_raw: WebSocketClient):
ws = ws_raw
await ws.send_json({"type": "connection_init", "payload": "gonna fail"})
await ws.receive(timeout=2)
assert ws.closed
assert ws.close_code == 4400
assert ws.close_reason == "Invalid connection init payload"
@pytest.mark.parametrize(
"payload",
[[], "invalid value", 1],
)
async def test_rejects_connection_params_with_wrong_type(
payload: object, ws_raw: WebSocketClient
):
ws = ws_raw
await ws.send_json({"type": "connection_init", "payload": payload})
await ws.receive(timeout=2)
assert ws.closed
assert ws.close_code == 4400
assert ws.close_reason == "Invalid connection init payload"
# timings can sometimes fail currently. Until this test is rewritten when
# generator based subscriptions are implemented, mark it as flaky
@pytest.mark.xfail(reason="This test is flaky, see comment above")
async def test_subsciption_cancel_finalization_delay(ws: WebSocketClient):
# Test that when we cancel a subscription, the websocket isn't blocked
# while some complex finalization takes place.
delay = 0.1
await ws.send_message(
{
"id": "sub1",
"type": "subscribe",
"payload": {"query": f"subscription {{ longFinalizer(delay: {delay}) }}"},
}
)
next_message: NextMessage = await ws.receive_json()
assert_next(next_message, "sub1", {"longFinalizer": "hello"})
# now cancel the stubscription and send a new query. We expect the message
# to the new query to arrive immediately, without waiting for the finalizer
start = time.time()
await ws.send_message({"id": "sub1", "type": "complete"})
await ws.send_message(
{
"id": "sub2",
"type": "subscribe",
"payload": {"query": "query { hello }"},
}
)
while True:
next_or_complete_message: Union[
NextMessage, CompleteMessage
] = await ws.receive_json()
assert next_or_complete_message["type"] in ("next", "complete")
if next_or_complete_message["id"] == "sub2":
break
end = time.time()
elapsed = end - start
assert elapsed < delay
async def test_error_handler_for_timeout(http_client: HttpClient):
"""Test that the error handler is called when the timeout
task encounters an error.
"""
with contextlib.suppress(ImportError):
from tests.http.clients.channels import ChannelsHttpClient
if isinstance(http_client, ChannelsHttpClient):
pytest.skip("Can't patch on_init for this client")