Debian Codegraph @

tests/execution/test_subscribe.py

raw
1 import asyncio
2 from typing import Any, Callable, Dict, List
3
4 from graphql.execution import (
5 ExecutionResult,
6 MapAsyncIterator,
7 create_source_event_stream,
8 subscribe,
9 )
10 from graphql.language import parse
11 from graphql.pyutils import SimplePubSub
12 from graphql.type import (
13 GraphQLArgument,
14 GraphQLBoolean,
15 GraphQLField,
16 GraphQLInt,
17 GraphQLList,
18 GraphQLObjectType,
19 GraphQLSchema,
20 GraphQLString,
21 )
22 from pytest import mark, raises
23
24 try:
25 anext
26 except NameError: # pragma: no cover (Python < 3.10)
27 # noinspection PyShadowingBuiltins
28 async def anext(iterator):
29 """Return the next item from an async iterator."""
30 return await iterator.__anext__()
31
32
33 Email = Dict # should become a TypedDict once we require Python 3.8
34
35 EmailType = GraphQLObjectType(
36 "Email",
37 {
38 "from": GraphQLField(GraphQLString),
39 "subject": GraphQLField(GraphQLString),
40 "message": GraphQLField(GraphQLString),
41 "unread": GraphQLField(GraphQLBoolean),
42 },
43 )
44
45 InboxType = GraphQLObjectType(
46 "Inbox",
47 {
48 "total": GraphQLField(
49 GraphQLInt, resolve=lambda inbox, _info: len(inbox["emails"])
50 ),
51 "unread": GraphQLField(
52 GraphQLInt,
53 resolve=lambda inbox, _info: sum(
54 1 for email in inbox["emails"] if email["unread"]
55 ),
56 ),
57 "emails": GraphQLField(GraphQLList(EmailType)),
58 },
59 )
60
61 QueryType = GraphQLObjectType("Query", {"inbox": GraphQLField(InboxType)})
62
63 EmailEventType = GraphQLObjectType(
64 "EmailEvent", {"email": GraphQLField(EmailType), "inbox": GraphQLField(InboxType)}
65 )
66
67
68 email_schema = GraphQLSchema(
69 query=QueryType,
70 subscription=GraphQLObjectType(
71 "Subscription",
72 {
73 "importantEmail": GraphQLField(
74 EmailEventType,
75 args={"priority": GraphQLArgument(GraphQLInt)},
76 )
77 },
78 ),
79 )
80
81
82 def create_subscription(pubsub: SimplePubSub):
83 document = parse("""
84 subscription ($priority: Int = 0) {
85 importantEmail(priority: $priority) {
86 email {
87 from
88 subject
89 }
90 inbox {
91 unread
92 total
93 }
94 }
95 }
96 """)
97
98 emails: List[Email] = [
99 {
100 "from": "[email protected]",
101 "subject": "Hello",
102 "message": "Hello World",
103 "unread": False,
104 }
105 ]
106
107 def transform(new_email):
108 emails.append(new_email)
109
110 return {"importantEmail": {"email": new_email, "inbox": data["inbox"]}}
111
112 data: Dict[str, Any] = {
113 "inbox": {"emails": emails},
114 "importantEmail": pubsub.get_subscriber(transform),
115 }
116
117 return subscribe(email_schema, document, data)
118
119
120 DummyQueryType = GraphQLObjectType("Query", {"dummy": GraphQLField(GraphQLString)})
121
122
123 # Check all error cases when initializing the subscription.
124 def describe_subscription_initialization_phase():
125 @mark.asyncio
126 async def accepts_positional_arguments():
127 document = parse("""
128 subscription {
129 importantEmail
130 }
131 """)
132
133 async def empty_async_iterator(_info):
134 for value in (): # type: ignore
135 yield value # pragma: no cover
136
137 ai = await subscribe(
138 email_schema, document, {"importantEmail": empty_async_iterator}
139 )
140
141 with raises(StopAsyncIteration):
142 await anext(ai)
143 await ai.aclose() # type: ignore
144
145 @mark.asyncio
146 async def accepts_multiple_subscription_fields_defined_in_schema():
147 schema = GraphQLSchema(
148 query=DummyQueryType,
149 subscription=GraphQLObjectType(
150 "Subscription",
151 {
152 "foo": GraphQLField(GraphQLString),
153 "bar": GraphQLField(GraphQLString),
154 },
155 ),
156 )
157
158 async def foo_generator(_info):
159 yield {"foo": "FooValue"}
160
161 subscription = await subscribe(
162 schema, parse("subscription { foo }"), {"foo": foo_generator}
163 )
164 assert isinstance(subscription, MapAsyncIterator)
165
166 assert await anext(subscription) == ({"foo": "FooValue"}, None)
167
168 await subscription.aclose()
169
170 @mark.asyncio
171 async def accepts_type_definition_with_sync_subscribe_function():
172 async def foo_generator(_obj, _info):
173 yield {"foo": "FooValue"}
174
175 schema = GraphQLSchema(
176 query=DummyQueryType,
177 subscription=GraphQLObjectType(
178 "Subscription",
179 {"foo": GraphQLField(GraphQLString, subscribe=foo_generator)},
180 ),
181 )
182
183 subscription = await subscribe(schema, parse("subscription { foo }"))
184 assert isinstance(subscription, MapAsyncIterator)
185
186 assert await anext(subscription) == ({"foo": "FooValue"}, None)
187
188 await subscription.aclose()
189
190 @mark.asyncio
191 async def accepts_type_definition_with_async_subscribe_function():
192 async def foo_generator(_obj, _info):
193 await asyncio.sleep(0)
194 yield {"foo": "FooValue"}
195
196 schema = GraphQLSchema(
197 query=DummyQueryType,
198 subscription=GraphQLObjectType(
199 "Subscription",
200 {"foo": GraphQLField(GraphQLString, subscribe=foo_generator)},
201 ),
202 )
203
204 subscription = await subscribe(schema, parse("subscription { foo }"))
205 assert isinstance(subscription, MapAsyncIterator)
206
207 assert await anext(subscription) == ({"foo": "FooValue"}, None)
208
209 await subscription.aclose()
210
211 @mark.asyncio
212 async def uses_a_custom_default_subscribe_field_resolver():
213 schema = GraphQLSchema(
214 query=DummyQueryType,
215 subscription=GraphQLObjectType(
216 "Subscription", {"foo": GraphQLField(GraphQLString)}
217 ),
218 )
219
220 class Root:
221 @staticmethod
222 async def custom_foo():
223 yield {"foo": "FooValue"}
224
225 subscription = await subscribe(
226 schema,
227 document=parse("subscription { foo }"),
228 root_value=Root(),
229 subscribe_field_resolver=lambda root, _info: root.custom_foo(),
230 )
231 assert isinstance(subscription, MapAsyncIterator)
232
233 assert await anext(subscription) == (
234 {"foo": "FooValue"},
235 None,
236 )
237
238 await subscription.aclose()
239
240 @mark.asyncio
241 async def should_only_resolve_the_first_field_of_invalid_multi_field():
242 did_resolve = {"foo": False, "bar": False}
243
244 async def subscribe_foo(_obj, _info):
245 did_resolve["foo"] = True
246 yield {"foo": "FooValue"}
247
248 async def subscribe_bar(_obj, _info): # pragma: no cover
249 did_resolve["bar"] = True
250 yield {"bar": "BarValue"}
251
252 schema = GraphQLSchema(
253 query=DummyQueryType,
254 subscription=GraphQLObjectType(
255 "Subscription",
256 {
257 "foo": GraphQLField(GraphQLString, subscribe=subscribe_foo),
258 "bar": GraphQLField(GraphQLString, subscribe=subscribe_bar),
259 },
260 ),
261 )
262
263 subscription = await subscribe(schema, parse("subscription { foo bar }"))
264 assert isinstance(subscription, MapAsyncIterator)
265
266 assert await anext(subscription) == (
267 {"foo": "FooValue", "bar": None},
268 None,
269 )
270
271 assert did_resolve == {"foo": True, "bar": False}
272
273 await subscription.aclose()
274
275 @mark.asyncio
276 async def throws_an_error_if_some_of_required_arguments_are_missing():
277 document = parse("subscription { foo }")
278
279 schema = GraphQLSchema(
280 query=DummyQueryType,
281 subscription=GraphQLObjectType(
282 "Subscription", {"foo": GraphQLField(GraphQLString)}
283 ),
284 )
285
286 with raises(TypeError, match="^Expected None to be a GraphQL schema\\.$"):
287 await subscribe(None, document) # type: ignore
288
289 with raises(TypeError, match="missing .* positional argument: 'schema'"):
290 await subscribe(document=document) # type: ignore
291
292 with raises(TypeError, match="^Must provide document\\.$"):
293 await subscribe(schema, None) # type: ignore
294
295 with raises(TypeError, match="missing .* positional argument: 'document'"):
296 await subscribe(schema=schema) # type: ignore
297
298 @mark.asyncio
299 async def resolves_to_an_error_if_schema_does_not_support_subscriptions():
300 schema = GraphQLSchema(query=DummyQueryType)
301 document = parse("subscription { unknownField }")
302
303 result = await subscribe(schema, document)
304
305 assert result == (
306 None,
307 [
308 {
309 "message": "Schema is not configured to execute"
310 " subscription operation.",
311 "locations": [(1, 1)],
312 }
313 ],
314 )
315
316 @mark.asyncio
317 async def resolves_to_an_error_for_unknown_subscription_field():
318 schema = GraphQLSchema(
319 query=DummyQueryType,
320 subscription=GraphQLObjectType(
321 "Subscription", {"foo": GraphQLField(GraphQLString)}
322 ),
323 )
324 document = parse("subscription { unknownField }")
325
326 result = await subscribe(schema, document)
327 assert result == (
328 None,
329 [
330 {
331 "message": "The subscription field 'unknownField' is not defined.",
332 "locations": [(1, 16)],
333 }
334 ],
335 )
336
337 @mark.asyncio
338 async def should_pass_through_unexpected_errors_thrown_in_subscribe():
339 schema = GraphQLSchema(
340 query=DummyQueryType,
341 subscription=GraphQLObjectType(
342 "Subscription", {"foo": GraphQLField(GraphQLString)}
343 ),
344 )
345 with raises(TypeError, match="^Must provide document\\.$"):
346 await subscribe(schema=schema, document={}) # type: ignore
347
348 @mark.asyncio
349 @mark.filterwarnings("ignore:.* was never awaited:RuntimeWarning")
350 async def throws_an_error_if_subscribe_does_not_return_an_iterator():
351 schema = GraphQLSchema(
352 query=DummyQueryType,
353 subscription=GraphQLObjectType(
354 "Subscription",
355 {
356 "foo": GraphQLField(
357 GraphQLString, subscribe=lambda _obj, _info: "test"
358 )
359 },
360 ),
361 )
362
363 document = parse("subscription { foo }")
364
365 with raises(TypeError) as exc_info:
366 await subscribe(schema, document)
367
368 assert str(exc_info.value) == (
369 "Subscription field must return AsyncIterable. Received: 'test'."
370 )
371
372 @mark.asyncio
373 async def resolves_to_an_error_for_subscription_resolver_errors():
374 async def subscribe_with_fn(subscribe_fn: Callable):
375 schema = GraphQLSchema(
376 query=DummyQueryType,
377 subscription=GraphQLObjectType(
378 "Subscription",
379 {"foo": GraphQLField(GraphQLString, subscribe=subscribe_fn)},
380 ),
381 )
382 document = parse("subscription { foo }")
383 result = await subscribe(schema, document)
384
385 assert await create_source_event_stream(schema, document) == result
386 return result
387
388 expected_result = (
389 None,
390 [
391 {
392 "message": "test error",
393 "locations": [(1, 16)],
394 "path": ["foo"],
395 }
396 ],
397 )
398
399 # Returning an error
400 def return_error(_obj, _info):
401 return TypeError("test error")
402
403 assert await subscribe_with_fn(return_error) == expected_result
404
405 # Throwing an error
406 def throw_error(*_args):
407 raise TypeError("test error")
408
409 assert await subscribe_with_fn(throw_error) == expected_result
410
411 # Resolving to an error
412 async def resolve_error(*_args):
413 return TypeError("test error")
414
415 assert await subscribe_with_fn(resolve_error) == expected_result
416
417 # Rejecting with an error
418 async def reject_error(*_args):
419 return TypeError("test error")
420
421 assert await subscribe_with_fn(reject_error) == expected_result
422
423 @mark.asyncio
424 async def resolves_to_an_error_if_variables_were_wrong_type():
425 schema = GraphQLSchema(
426 query=DummyQueryType,
427 subscription=GraphQLObjectType(
428 "Subscription",
429 {
430 "foo": GraphQLField(
431 GraphQLString, {"arg": GraphQLArgument(GraphQLInt)}
432 )
433 },
434 ),
435 )
436
437 variable_values = {"arg": "meow"}
438 document = parse("""
439 subscription ($arg: Int) {
440 foo(arg: $arg)
441 }
442 """)
443
444 # If we receive variables that cannot be coerced correctly, subscribe() will
445 # resolve to an ExecutionResult that contains an informative error description.
446 result = await subscribe(schema, document, variable_values=variable_values)
447
448 assert isinstance(result, ExecutionResult)
449
450 assert result == (
451 None,
452 [
453 {
454 "message": "Variable '$arg' got invalid value 'meow';"
455 " Int cannot represent non-integer value: 'meow'",
456 "locations": [(2, 27)],
457 }
458 ],
459 )
460
461 errors = result.errors
462 assert errors
463 assert errors[0].original_error
464
465
466 # Once a subscription returns a valid AsyncIterator, it can still yield errors.
467 def describe_subscription_publish_phase():
468 @mark.asyncio
469 async def produces_a_payload_for_multiple_subscribe_in_same_subscription():
470 pubsub = SimplePubSub()
471
472 subscription = await create_subscription(pubsub)
473 assert isinstance(subscription, MapAsyncIterator)
474
475 second_subscription = await create_subscription(pubsub)
476 assert isinstance(subscription, MapAsyncIterator)
477
478 payload1 = anext(subscription)
479 payload2 = anext(second_subscription)
480
481 assert (
482 pubsub.emit(
483 {
484 "from": "[email protected]",
485 "subject": "Alright",
486 "message": "Tests are good",
487 "unread": True,
488 }
489 )
490 is True
491 )
492
493 expected_payload = {
494 "importantEmail": {
495 "email": {"from": "[email protected]", "subject": "Alright"},
496 "inbox": {"unread": 1, "total": 2},
497 }
498 }
499
500 assert await payload1 == (expected_payload, None)
501 assert await payload2 == (expected_payload, None)
502
503 @mark.asyncio
504 async def produces_a_payload_per_subscription_event():
505 pubsub = SimplePubSub()
506 subscription = await create_subscription(pubsub)
507 assert isinstance(subscription, MapAsyncIterator)
508
509 # Wait for the next subscription payload.
510 payload = anext(subscription)
511
512 # A new email arrives!
513 assert (
514 pubsub.emit(
515 {
516 "from": "[email protected]",
517 "subject": "Alright",
518 "message": "Tests are good",
519 "unread": True,
520 }
521 )
522 is True
523 )
524
525 # The previously waited on payload now has a value.
526 assert await payload == (
527 {
528 "importantEmail": {
529 "email": {"from": "[email protected]", "subject": "Alright"},
530 "inbox": {"unread": 1, "total": 2},
531 }
532 },
533 None,
534 )
535
536 # Another new email arrives, before anext(subscription) is called.
537 assert (
538 pubsub.emit(
539 {
540 "from": "[email protected]",
541 "subject": "Tools",
542 "message": "I <3 making things",
543 "unread": True,
544 }
545 )
546 is True
547 )
548
549 # The next waited on payload will have a value.
550 assert await anext(subscription) == (
551 {
552 "importantEmail": {
553 "email": {"from": "[email protected]", "subject": "Tools"},
554 "inbox": {"unread": 2, "total": 3},
555 }
556 },
557 None,
558 )
559
560 # The client decides to disconnect.
561 # noinspection PyUnresolvedReferences
562 await subscription.aclose()
563
564 # Which may result in disconnecting upstream services as well.
565 assert (
566 pubsub.emit(
567 {
568 "from": "[email protected]",
569 "subject": "Important",
570 "message": "Read me please",
571 "unread": True,
572 }
573 )
574 is False
575 ) # No more listeners.
576
577 # Awaiting subscription after closing it results in completed results.
578 with raises(StopAsyncIteration):
579 assert await anext(subscription)
580
581 @mark.asyncio
582 async def produces_a_payload_when_there_are_multiple_events():
583 pubsub = SimplePubSub()
584 subscription = await create_subscription(pubsub)
585 assert isinstance(subscription, MapAsyncIterator)
586
587 payload = anext(subscription)
588
589 # A new email arrives!
590 assert (
591 pubsub.emit(
592 {
593 "from": "[email protected]",
594 "subject": "Alright",
595 "message": "Tests are good",
596 "unread": True,
597 }
598 )
599 is True
600 )
601
602 assert await payload == (
603 {
604 "importantEmail": {
605 "email": {"from": "[email protected]", "subject": "Alright"},
606 "inbox": {"unread": 1, "total": 2},
607 }
608 },
609 None,
610 )
611
612 payload = anext(subscription)
613
614 # A new email arrives!
615 assert (
616 pubsub.emit(
617 {
618 "from": "[email protected]",
619 "subject": "Alright 2",
620 "message": "Tests are good 2",
621 "unread": True,
622 }
623 )
624 is True
625 )
626
627 assert await payload == (
628 {
629 "importantEmail": {
630 "email": {"from": "[email protected]", "subject": "Alright 2"},
631 "inbox": {"unread": 2, "total": 3},
632 }
633 },
634 None,
635 )
636
637 @mark.asyncio
638 async def should_not_trigger_when_subscription_is_already_done():
639 pubsub = SimplePubSub()
640 subscription = await create_subscription(pubsub)
641 assert isinstance(subscription, MapAsyncIterator)
642
643 payload = anext(subscription)
644
645 # A new email arrives!
646 assert (
647 pubsub.emit(
648 {
649 "from": "[email protected]",
650 "subject": "Alright",
651 "message": "Tests are good",
652 "unread": True,
653 }
654 )
655 is True
656 )
657
658 assert await payload == (
659 {
660 "importantEmail": {
661 "email": {"from": "[email protected]", "subject": "Alright"},
662 "inbox": {"unread": 1, "total": 2},
663 }
664 },
665 None,
666 )
667
668 payload = anext(subscription)
669 await subscription.aclose()
670
671 # A new email arrives!
672 assert (
673 pubsub.emit(
674 {
675 "from": "[email protected]",
676 "subject": "Alright 2",
677 "message": "Tests are good 2",
678 "unread": True,
679 }
680 )
681 is False
682 )
683
684 with raises(StopAsyncIteration):
685 await payload
686
687 @mark.asyncio
688 async def should_not_trigger_when_subscription_is_thrown():
689 pubsub = SimplePubSub()
690 subscription = await create_subscription(pubsub)
691 assert isinstance(subscription, MapAsyncIterator)
692
693 payload = anext(subscription)
694
695 # A new email arrives!
696 assert (
697 pubsub.emit(
698 {
699 "from": "[email protected]",
700 "subject": "Alright",
701 "message": "Tests are good",
702 "unread": True,
703 }
704 )
705 is True
706 )
707
708 assert await payload == (
709 {
710 "importantEmail": {
711 "email": {"from": "[email protected]", "subject": "Alright"},
712 "inbox": {"unread": 1, "total": 2},
713 }
714 },
715 None,
716 )
717
718 payload = anext(subscription)
719
720 # Throw error
721 with raises(RuntimeError) as exc_info:
722 await subscription.athrow(RuntimeError("ouch"))
723 assert str(exc_info.value) == "ouch"
724
725 with raises(StopAsyncIteration):
726 await payload
727
728 @mark.asyncio
729 async def event_order_is_correct_for_multiple_publishes():
730 pubsub = SimplePubSub()
731 subscription = await create_subscription(pubsub)
732 assert isinstance(subscription, MapAsyncIterator)
733
734 payload = anext(subscription)
735
736 # A new email arrives!
737 assert (
738 pubsub.emit(
739 {
740 "from": "[email protected]",
741 "subject": "Message",
742 "message": "Tests are good",
743 "unread": True,
744 }
745 )
746 is True
747 )
748
749 # A new email arrives!
750 assert (
751 pubsub.emit(
752 {
753 "from": "[email protected]",
754 "subject": "Message 2",
755 "message": "Tests are good 2",
756 "unread": True,
757 }
758 )
759 is True
760 )
761
762 assert await payload == (
763 {
764 "importantEmail": {
765 "email": {"from": "[email protected]", "subject": "Message"},
766 "inbox": {"unread": 2, "total": 3},
767 }
768 },
769 None,
770 )
771
772 payload = anext(subscription)
773
774 assert await payload == (
775 {
776 "importantEmail": {
777 "email": {"from": "[email protected]", "subject": "Message 2"},
778 "inbox": {"unread": 2, "total": 3},
779 }
780 },
781 None,
782 )
783
784 @mark.asyncio
785 async def should_handle_error_during_execution_of_source_event():
786 async def generate_messages(_obj, _info):
787 yield "Hello"
788 yield "Goodbye"
789 yield "Bonjour"
790
791 def resolve_message(message, _info):
792 if message == "Goodbye":
793 raise RuntimeError("Never leave.")
794 return message
795
796 schema = GraphQLSchema(
797 query=DummyQueryType,
798 subscription=GraphQLObjectType(
799 "Subscription",
800 {
801 "newMessage": GraphQLField(
802 GraphQLString,
803 subscribe=generate_messages,
804 resolve=resolve_message,
805 )
806 },
807 ),
808 )
809
810 document = parse("subscription { newMessage }")
811 subscription = await subscribe(schema, document)
812 assert isinstance(subscription, MapAsyncIterator)
813
814 assert await anext(subscription) == ({"newMessage": "Hello"}, None)
815
816 # An error in execution is presented as such.
817 assert await anext(subscription) == (
818 {"newMessage": None},
819 [
820 {
821 "message": "Never leave.",
822 "locations": [(1, 16)],
823 "path": ["newMessage"],
824 }
825 ],
826 )
827
828 # However that does not close the response event stream.
829 # Subsequent events are still executed.
830 assert await anext(subscription) == ({"newMessage": "Bonjour"}, None)
831
832 @mark.asyncio
833 async def should_pass_through_error_thrown_in_source_event_stream():
834 async def generate_messages(_obj, _info):
835 yield "Hello"
836 raise RuntimeError("test error")
837
838 def resolve_message(message, _info):
839 return message
840
841 schema = GraphQLSchema(
842 query=DummyQueryType,
843 subscription=GraphQLObjectType(
844 "Subscription",
845 {
846 "newMessage": GraphQLField(
847 GraphQLString,
848 resolve=resolve_message,
849 subscribe=generate_messages,
850 )
851 },
852 ),
853 )
854
855 document = parse("subscription { newMessage }")
856 subscription = await subscribe(schema, document)
857 assert isinstance(subscription, MapAsyncIterator)
858
859 assert await anext(subscription) == ({"newMessage": "Hello"}, None)
860
861 with raises(RuntimeError) as exc_info:
862 await anext(subscription)
863
864 assert str(exc_info.value) == "test error"
865
866 with raises(StopAsyncIteration):
867 await anext(subscription)
868
869 @mark.asyncio
870 async def should_work_with_async_resolve_function():
871 async def generate_messages(_obj, _info):
872 yield "Hello"
873
874 def resolve_message(message, _info):
875 return message
876
877 schema = GraphQLSchema(
878 query=QueryType,
879 subscription=GraphQLObjectType(
880 "Subscription",
881 {
882 "newMessage": GraphQLField(
883 GraphQLString,
884 resolve=resolve_message,
885 subscribe=generate_messages,
886 )
887 },
888 ),
889 )
890
891 document = parse("subscription { newMessage }")
892 subscription = await subscribe(schema, document)
893 assert isinstance(subscription, MapAsyncIterator)
894
895 assert await anext(subscription) == ({"newMessage": "Hello"}, None)