File: test_executor.py

package info (click to toggle)
graphql-core 3.2.6-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, trixie
  • size: 5,384 kB
  • sloc: python: 45,812; makefile: 26; sh: 13
file content (1144 lines) | stat: -rw-r--r-- 34,948 bytes parent folder | download | duplicates (2)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
import asyncio
from typing import Any, Awaitable, Optional, cast

from graphql.error import GraphQLError
from graphql.execution import execute, execute_sync
from graphql.language import FieldNode, OperationDefinitionNode, parse
from graphql.pyutils import Undefined, inspect
from graphql.type import (
    GraphQLArgument,
    GraphQLBoolean,
    GraphQLField,
    GraphQLInt,
    GraphQLInterfaceType,
    GraphQLList,
    GraphQLNonNull,
    GraphQLObjectType,
    GraphQLResolveInfo,
    GraphQLScalarType,
    GraphQLSchema,
    GraphQLString,
    GraphQLUnionType,
    ResponsePath,
)
from pytest import mark, raises


def describe_execute_handles_basic_execution_tasks():
    # noinspection PyTypeChecker
    def throws_if_no_document_is_provided():
        schema = GraphQLSchema(
            GraphQLObjectType("Type", {"a": GraphQLField(GraphQLString)})
        )

        with raises(TypeError) as exc_info:
            assert execute_sync(schema=schema, document=None)  # type: ignore

        assert str(exc_info.value) == "Must provide document."

    # noinspection PyTypeChecker
    def throws_if_no_schema_is_provided():
        document = parse("{ field }")

        with raises(TypeError) as exc_info:
            assert execute_sync(schema=None, document=document)  # type: ignore

        assert str(exc_info.value) == "Expected None to be a GraphQL schema."

    def throws_on_invalid_variables():
        schema = GraphQLSchema(
            GraphQLObjectType(
                "Type",
                {
                    "fieldA": GraphQLField(
                        GraphQLString, args={"argA": GraphQLArgument(GraphQLInt)}
                    )
                },
            )
        )
        document = parse(
            """
            query ($a: Int) {
              fieldA(argA: $a)
            }
            """
        )
        variable_values = "{'a': 1}"

        with raises(TypeError) as exc_info:
            assert execute_sync(
                schema=schema,
                document=document,
                variable_values=variable_values,  # type: ignore
            )

        assert str(exc_info.value) == (
            "Variable values must be provided as a dictionary"
            " with variable names as keys. Perhaps look to see"
            " if an unparsed JSON string was provided."
        )

    def accepts_positional_arguments():
        schema = GraphQLSchema(
            GraphQLObjectType(
                "Type",
                {"a": GraphQLField(GraphQLString, resolve=lambda obj, *args: obj)},
            )
        )

        result = execute_sync(schema, parse("{ a }"), "rootValue")

        assert result == ({"a": "rootValue"}, None)

    @mark.asyncio
    async def executes_arbitrary_code():
        # noinspection PyMethodMayBeStatic,PyMethodMayBeStatic
        class Data:
            def a(self, _info):
                return "Apple"

            def b(self, _info):
                return "Banana"

            def c(self, _info):
                return "Cookie"

            def d(self, _info):
                return "Donut"

            def e(self, _info):
                return "Egg"

            f = "Fish"

            # Called only by DataType::pic static resolver
            def pic(self, _info, size: int):
                return f"Pic of size: {size}"

            def deep(self, _info):
                return DeepData()

            def promise(self, _info):
                return promise_data()

        # noinspection PyMethodMayBeStatic,PyMethodMayBeStatic
        class DeepData:
            def a(self, _info):
                return "Already Been Done"

            def b(self, _info):
                return "Boring"

            def c(self, _info):
                return ["Contrived", None, "Confusing"]

            def deeper(self, _info):
                return [Data(), None, Data()]

        async def promise_data():
            await asyncio.sleep(0)
            return Data()

        DeepDataType: GraphQLObjectType

        DataType = GraphQLObjectType(
            "DataType",
            lambda: {
                "a": GraphQLField(GraphQLString),
                "b": GraphQLField(GraphQLString),
                "c": GraphQLField(GraphQLString),
                "d": GraphQLField(GraphQLString),
                "e": GraphQLField(GraphQLString),
                "f": GraphQLField(GraphQLString),
                "pic": GraphQLField(
                    GraphQLString,
                    args={"size": GraphQLArgument(GraphQLInt)},
                    resolve=lambda obj, info, size: obj.pic(info, size),
                ),
                "deep": GraphQLField(DeepDataType),
                "promise": GraphQLField(DataType),
            },
        )

        DeepDataType = GraphQLObjectType(
            "DeepDataType",
            {
                "a": GraphQLField(GraphQLString),
                "b": GraphQLField(GraphQLString),
                "c": GraphQLField(GraphQLList(GraphQLString)),
                "deeper": GraphQLField(GraphQLList(DataType)),
            },
        )

        document = parse(
            """
            query ($size: Int) {
              a,
              b,
              x: c
              ...c
              f
              ...on DataType {
                pic(size: $size)
                promise {
                  a
                }
              }
              deep {
                a
                b
                c
                deeper {
                  a
                  b
                }
              }
            }

            fragment c on DataType {
              d
              e
            }
            """
        )

        awaitable_result = execute(
            GraphQLSchema(DataType), document, Data(), variable_values={"size": 100}
        )
        assert isinstance(awaitable_result, Awaitable)
        result = await awaitable_result

        assert result == (
            {
                "a": "Apple",
                "b": "Banana",
                "x": "Cookie",
                "d": "Donut",
                "e": "Egg",
                "f": "Fish",
                "pic": "Pic of size: 100",
                "promise": {"a": "Apple"},
                "deep": {
                    "a": "Already Been Done",
                    "b": "Boring",
                    "c": ["Contrived", None, "Confusing"],
                    "deeper": [
                        {"a": "Apple", "b": "Banana"},
                        None,
                        {"a": "Apple", "b": "Banana"},
                    ],
                },
            },
            None,
        )

    def merges_parallel_fragments():
        Type = GraphQLObjectType(
            "Type",
            lambda: {
                "a": GraphQLField(GraphQLString, resolve=lambda *_args: "Apple"),
                "b": GraphQLField(GraphQLString, resolve=lambda *_args: "Banana"),
                "c": GraphQLField(GraphQLString, resolve=lambda *_args: "Cherry"),
                "deep": GraphQLField(Type, resolve=lambda *_args: {}),
            },
        )
        schema = GraphQLSchema(Type)

        ast = parse(
            """
            { a, ...FragOne, ...FragTwo }

            fragment FragOne on Type {
              b
              deep { b, deeper: deep { b } }
            }

            fragment FragTwo on Type {
              c
              deep { c, deeper: deep { c } }
            }
            """
        )

        result = execute_sync(schema, ast)
        assert result == (
            {
                "a": "Apple",
                "b": "Banana",
                "c": "Cherry",
                "deep": {
                    "b": "Banana",
                    "c": "Cherry",
                    "deeper": {"b": "Banana", "c": "Cherry"},
                },
            },
            None,
        )

    def provides_info_about_current_execution_state():
        resolved_infos = []

        def resolve(_obj, info):
            resolved_infos.append(info)

        test_type = GraphQLObjectType(
            "Test", {"test": GraphQLField(GraphQLString, resolve=resolve)}
        )

        schema = GraphQLSchema(test_type)

        document = parse("query ($var: String) { result: test }")
        root_value = {"root": "val"}
        variable_values = {"var": "abc"}
        execute_sync(schema, document, root_value, variable_values=variable_values)

        assert len(resolved_infos) == 1
        operation = cast(OperationDefinitionNode, document.definitions[0])
        assert operation and operation.kind == "operation_definition"
        field = cast(FieldNode, operation.selection_set.selections[0])

        assert resolved_infos[0] == GraphQLResolveInfo(
            field_name="test",
            field_nodes=[field],
            return_type=GraphQLString,
            parent_type=cast(GraphQLObjectType, schema.query_type),
            path=ResponsePath(None, "result", "Test"),
            schema=schema,
            fragments={},
            root_value=root_value,
            operation=operation,
            variable_values=variable_values,
            context=None,
            is_awaitable=resolved_infos[0].is_awaitable,
        )

    def it_populates_path_correctly_with_complex_types():
        path: Optional[ResponsePath] = None

        def resolve(_val, info):
            nonlocal path
            path = info.path

        def resolve_type(_val, _info, _type):
            return "SomeObject"

        some_object = GraphQLObjectType(
            "SomeObject", {"test": GraphQLField(GraphQLString, resolve=resolve)}
        )
        some_union = GraphQLUnionType(
            "SomeUnion", [some_object], resolve_type=resolve_type
        )
        test_type = GraphQLObjectType(
            "SomeQuery",
            {
                "test": GraphQLField(
                    GraphQLNonNull(GraphQLList(GraphQLNonNull(some_union)))
                )
            },
        )
        schema = GraphQLSchema(test_type)
        root_value: Any = {"test": [{}]}
        document = parse(
            """
            query {
              l1: test {
                ... on SomeObject {
                  l2: test
                }
              }
            }
            """
        )

        execute_sync(schema, document, root_value)

        assert path is not None
        prev, key, typename = path
        assert key == "l2"
        assert typename == "SomeObject"
        prev, key, typename = prev
        assert key == 0
        assert typename is None
        prev, key, typename = prev
        assert key == "l1"
        assert typename == "SomeQuery"
        assert prev is None

    def threads_root_value_context_correctly():
        resolved_values = []

        class Data:
            context_thing = "thing"

        def resolve(obj, _info):
            resolved_values.append(obj)

        schema = GraphQLSchema(
            GraphQLObjectType(
                "Type", {"a": GraphQLField(GraphQLString, resolve=resolve)}
            )
        )

        document = parse("query Example { a }")
        root_value = Data()
        execute_sync(schema, document, root_value)

        assert len(resolved_values) == 1
        assert resolved_values[0] is root_value

    def correctly_threads_arguments():
        resolved_args = []

        def resolve(_obj, _info, **args):
            resolved_args.append(args)

        schema = GraphQLSchema(
            GraphQLObjectType(
                "Type",
                {
                    "b": GraphQLField(
                        GraphQLString,
                        args={
                            "numArg": GraphQLArgument(GraphQLInt),
                            "stringArg": GraphQLArgument(GraphQLString),
                        },
                        resolve=resolve,
                    )
                },
            )
        )

        document = parse(
            """
            query Example {
              b(numArg: 123, stringArg: "foo")
            }
            """
        )

        execute_sync(schema, document)

        assert len(resolved_args) == 1
        assert resolved_args[0] == {"numArg": 123, "stringArg": "foo"}

    @mark.asyncio
    async def nulls_out_error_subtrees():
        document = parse(
            """
            {
              syncOk
              syncError
              syncRawError
              syncReturnError
              syncReturnErrorList
              asyncOk
              asyncError
              asyncRawError
              asyncReturnError
              asyncReturnErrorWithExtensions
            }
            """
        )

        schema = GraphQLSchema(
            GraphQLObjectType(
                "Type",
                {
                    "syncOk": GraphQLField(GraphQLString),
                    "syncError": GraphQLField(GraphQLString),
                    "syncRawError": GraphQLField(GraphQLString),
                    "syncReturnError": GraphQLField(GraphQLString),
                    "syncReturnErrorList": GraphQLField(GraphQLList(GraphQLString)),
                    "asyncOk": GraphQLField(GraphQLString),
                    "asyncError": GraphQLField(GraphQLString),
                    "asyncErrorWithExtensions": GraphQLField(GraphQLString),
                    "asyncRawError": GraphQLField(GraphQLString),
                    "asyncReturnError": GraphQLField(GraphQLString),
                    "asyncReturnErrorWithExtensions": GraphQLField(GraphQLString),
                },
            )
        )

        # noinspection PyPep8Naming,PyMethodMayBeStatic
        class Data:
            def syncOk(self, _info):
                return "sync ok"

            def syncError(self, _info):
                raise GraphQLError("Error getting syncError")

            def syncRawError(self, _info):
                raise Exception("Error getting syncRawError")

            def syncReturnError(self, _info):
                return Exception("Error getting syncReturnError")

            def syncReturnErrorList(self, _info):
                return [
                    "sync0",
                    Exception("Error getting syncReturnErrorList1"),
                    "sync2",
                    Exception("Error getting syncReturnErrorList3"),
                ]

            async def asyncOk(self, _info):
                return "async ok"

            async def asyncError(self, _info):
                raise GraphQLError("Error getting asyncError")

            async def asyncRawError(self, _info):
                raise Exception("Error getting asyncRawError")

            async def asyncReturnError(self, _info):
                return GraphQLError("Error getting asyncReturnError")

            async def asyncReturnErrorWithExtensions(self, _info):
                return GraphQLError(
                    "Error getting asyncReturnErrorWithExtensions",
                    extensions={"foo": "bar"},
                )

        awaitable_result = execute(schema, document, Data())
        assert isinstance(awaitable_result, Awaitable)
        result = await awaitable_result

        assert result == (
            {
                "syncOk": "sync ok",
                "syncError": None,
                "syncRawError": None,
                "syncReturnError": None,
                "syncReturnErrorList": ["sync0", None, "sync2", None],
                "asyncOk": "async ok",
                "asyncError": None,
                "asyncRawError": None,
                "asyncReturnError": None,
                "asyncReturnErrorWithExtensions": None,
            },
            [
                {
                    "message": "Error getting syncError",
                    "locations": [(4, 15)],
                    "path": ["syncError"],
                },
                {
                    "message": "Error getting syncRawError",
                    "locations": [(5, 15)],
                    "path": ["syncRawError"],
                },
                {
                    "message": "Error getting syncReturnError",
                    "locations": [(6, 15)],
                    "path": ["syncReturnError"],
                },
                {
                    "message": "Error getting syncReturnErrorList1",
                    "locations": [(7, 15)],
                    "path": ["syncReturnErrorList", 1],
                },
                {
                    "message": "Error getting syncReturnErrorList3",
                    "locations": [(7, 15)],
                    "path": ["syncReturnErrorList", 3],
                },
                {
                    "message": "Error getting asyncError",
                    "locations": [(9, 15)],
                    "path": ["asyncError"],
                },
                {
                    "message": "Error getting asyncRawError",
                    "locations": [(10, 15)],
                    "path": ["asyncRawError"],
                },
                {
                    "message": "Error getting asyncReturnError",
                    "locations": [(11, 15)],
                    "path": ["asyncReturnError"],
                },
                {
                    "message": "Error getting asyncReturnErrorWithExtensions",
                    "locations": [(12, 15)],
                    "path": ["asyncReturnErrorWithExtensions"],
                    "extensions": {"foo": "bar"},
                },
            ],
        )

    @mark.filterwarnings("ignore:.* was never awaited:RuntimeWarning")
    def handles_sync_errors_combined_with_async_ones():
        is_async_resolver_finished = False

        async def async_resolver(_obj, _info):
            nonlocal is_async_resolver_finished
            is_async_resolver_finished = True  # pragma: no cover

        schema = GraphQLSchema(
            GraphQLObjectType(
                "Query",
                {
                    "syncNullError": GraphQLField(
                        GraphQLNonNull(GraphQLString), resolve=lambda _obj, _info: None
                    ),
                    "asyncNullError": GraphQLField(
                        GraphQLNonNull(GraphQLString), resolve=async_resolver
                    ),
                },
            )
        )

        document = parse(
            """
            {
              asyncNullError
              syncNullError
            }
            """
        )

        result = execute(schema, document)

        assert is_async_resolver_finished is False

        assert result == (
            None,
            [
                {
                    "message": "Cannot return null"
                    " for non-nullable field Query.syncNullError.",
                    "locations": [(4, 15)],
                    "path": ["syncNullError"],
                }
            ],
        )

    @mark.filterwarnings("ignore:.* was never awaited:RuntimeWarning")
    def full_response_path_is_included_for_non_nullable_fields():
        def resolve_ok(*_args):
            return {}

        def resolve_error(*_args):
            raise Exception("Catch me if you can")

        A = GraphQLObjectType(
            "A",
            lambda: {
                "nullableA": GraphQLField(A, resolve=resolve_ok),
                "nonNullA": GraphQLField(GraphQLNonNull(A), resolve=resolve_ok),
                "throws": GraphQLField(GraphQLNonNull(A), resolve=resolve_error),
            },
        )

        schema = GraphQLSchema(
            GraphQLObjectType(
                "query", lambda: {"nullableA": GraphQLField(A, resolve=resolve_ok)}
            )
        )

        document = parse(
            """
            query {
              nullableA {
                aliasedA: nullableA {
                  nonNullA {
                    anotherA: nonNullA {
                      throws
                    }
                  }
                }
              }
            }
            """
        )

        assert execute_sync(schema, document) == (
            {"nullableA": {"aliasedA": None}},
            [
                {
                    "message": "Catch me if you can",
                    "locations": [(7, 23)],
                    "path": ["nullableA", "aliasedA", "nonNullA", "anotherA", "throws"],
                }
            ],
        )

    @mark.filterwarnings("ignore:.* was never awaited:RuntimeWarning")
    def uses_the_inline_operation_if_no_operation_name_is_provided():
        schema = GraphQLSchema(
            GraphQLObjectType("Type", {"a": GraphQLField(GraphQLString)})
        )

        document = parse("{ a }")

        class Data:
            a = "b"

        result = execute_sync(schema, document, Data())
        assert result == ({"a": "b"}, None)

    @mark.filterwarnings("ignore:.* was never awaited:RuntimeWarning")
    def uses_the_only_operation_if_no_operation_name_is_provided():
        schema = GraphQLSchema(
            GraphQLObjectType("Type", {"a": GraphQLField(GraphQLString)})
        )

        document = parse("query Example { a }")

        class Data:
            a = "b"

        result = execute_sync(schema, document, Data())
        assert result == ({"a": "b"}, None)

    @mark.filterwarnings("ignore:.* was never awaited:RuntimeWarning")
    def uses_the_named_operation_if_operation_name_is_provided():
        schema = GraphQLSchema(
            GraphQLObjectType("Type", {"a": GraphQLField(GraphQLString)})
        )

        document = parse(
            """
            query Example { first: a }
            query OtherExample { second: a }
            """
        )

        class Data:
            a = "b"

        result = execute_sync(schema, document, Data(), operation_name="OtherExample")
        assert result == ({"second": "b"}, None)

    def provides_error_if_no_operation_is_provided():
        schema = GraphQLSchema(
            GraphQLObjectType("Type", {"a": GraphQLField(GraphQLString)})
        )

        document = parse("fragment Example on Type { a }")

        class Data:
            a = "b"

        result = execute_sync(schema, document, Data())
        assert result == (None, [{"message": "Must provide an operation."}])

    def errors_if_no_operation_name_is_provided_with_multiple_operations():
        schema = GraphQLSchema(
            GraphQLObjectType("Type", {"a": GraphQLField(GraphQLString)})
        )

        document = parse(
            """
            query Example { a }
            query OtherExample { a }
            """
        )

        result = execute_sync(schema, document)
        assert result == (
            None,
            [
                {
                    "message": "Must provide operation name if query contains"
                    " multiple operations."
                }
            ],
        )

    def errors_if_unknown_operation_name_is_provided():
        schema = GraphQLSchema(
            GraphQLObjectType("Type", {"a": GraphQLField(GraphQLString)})
        )

        document = parse(
            """
            query Example { a }
            query OtherExample { a }
            """
        )

        result = execute_sync(schema, document, operation_name="UnknownExample")
        assert result == (
            None,
            [{"message": "Unknown operation named 'UnknownExample'."}],
        )

    def errors_if_empty_string_is_provided_as_operation_name():
        schema = GraphQLSchema(
            GraphQLObjectType("Type", {"a": GraphQLField(GraphQLString)})
        )

        document = parse("{ a }")

        result = execute_sync(schema, document, operation_name="")
        assert result == (
            None,
            [{"message": "Unknown operation named ''."}],
        )

    def uses_the_query_schema_for_queries():
        schema = GraphQLSchema(
            GraphQLObjectType("Q", {"a": GraphQLField(GraphQLString)}),
            GraphQLObjectType("M", {"c": GraphQLField(GraphQLString)}),
            GraphQLObjectType("S", {"a": GraphQLField(GraphQLString)}),
        )

        document = parse(
            """
            query Q { a }
            mutation M { c }
            subscription S { a }
            """
        )

        class Data:
            a = "b"
            c = "d"

        result = execute_sync(schema, document, Data(), operation_name="Q")
        assert result == ({"a": "b"}, None)

    def uses_the_mutation_schema_for_mutations():
        schema = GraphQLSchema(
            GraphQLObjectType("Q", {"a": GraphQLField(GraphQLString)}),
            GraphQLObjectType("M", {"c": GraphQLField(GraphQLString)}),
        )

        document = parse(
            """
            query Q { a }
            mutation M { c }
            """
        )

        class Data:
            a = "b"
            c = "d"

        result = execute_sync(schema, document, Data(), operation_name="M")
        assert result == ({"c": "d"}, None)

    def uses_the_subscription_schema_for_subscriptions():
        schema = GraphQLSchema(
            query=GraphQLObjectType("Q", {"a": GraphQLField(GraphQLString)}),
            subscription=GraphQLObjectType("S", {"a": GraphQLField(GraphQLString)}),
        )

        document = parse(
            """
            query Q { a }
            subscription S { a }
            """
        )

        class Data:
            a = "b"
            c = "d"

        result = execute_sync(schema, document, Data(), operation_name="S")
        assert result == ({"a": "b"}, None)

    def resolves_to_an_error_if_schema_does_not_support_operation():
        schema = GraphQLSchema(assume_valid=True)

        document = parse(
            """
            query Q { __typename }
            mutation M { __typename }
            subscription S { __typename }
            """
        )

        assert execute_sync(schema, document, operation_name="Q") == (
            None,
            [
                {
                    "message": "Schema is not configured to execute query operation.",
                    "locations": [(2, 13)],
                }
            ],
        )

        assert execute_sync(schema, document, operation_name="M") == (
            None,
            [
                {
                    "message": "Schema is not configured to execute"
                    " mutation operation.",
                    "locations": [(3, 13)],
                }
            ],
        )

        assert execute_sync(schema, document, operation_name="S") == (
            None,
            [
                {
                    "message": "Schema is not configured to execute"
                    " subscription operation.",
                    "locations": [(4, 13)],
                }
            ],
        )

    @mark.asyncio
    async def correct_field_ordering_despite_execution_order():
        schema = GraphQLSchema(
            GraphQLObjectType(
                "Type",
                {
                    "a": GraphQLField(GraphQLString),
                    "b": GraphQLField(GraphQLString),
                    "c": GraphQLField(GraphQLString),
                    "d": GraphQLField(GraphQLString),
                    "e": GraphQLField(GraphQLString),
                },
            )
        )

        document = parse("{ a, b, c, d, e}")

        # noinspection PyMethodMayBeStatic,PyMethodMayBeStatic
        class Data:
            def a(self, _info):
                return "a"

            async def b(self, _info):
                return "b"

            def c(self, _info):
                return "c"

            async def d(self, _info):
                return "d"

            def e(self, _info):
                return "e"

        awaitable_result = execute(schema, document, Data())
        assert isinstance(awaitable_result, Awaitable)
        result = await awaitable_result

        assert result == ({"a": "a", "b": "b", "c": "c", "d": "d", "e": "e"}, None)

    def avoids_recursion():
        schema = GraphQLSchema(
            GraphQLObjectType("Type", {"a": GraphQLField(GraphQLString)})
        )

        document = parse(
            """
            query Q {
              a
              ...Frag
              ...Frag
            }

            fragment Frag on Type {
              a,
              ...Frag
            }
            """
        )

        class Data:
            a = "b"

        result = execute_sync(schema, document, Data(), operation_name="Q")

        assert result == ({"a": "b"}, None)

    def ignores_missing_sub_selections_on_fields():
        some_type = GraphQLObjectType("SomeType", {"b": GraphQLField(GraphQLString)})
        schema = GraphQLSchema(
            GraphQLObjectType("Query", {"a": GraphQLField(some_type)})
        )
        document = parse("{ a }")
        root_value = {"a": {"b": "c"}}

        result = execute_sync(schema, document, root_value)
        assert result == ({"a": {}}, None)

    def does_not_include_illegal_fields_in_output():
        schema = GraphQLSchema(
            GraphQLObjectType("Q", {"a": GraphQLField(GraphQLString)})
        )

        document = parse("{ thisIsIllegalDoNotIncludeMe }")

        result = execute_sync(schema, document)

        assert result == ({}, None)

    def does_not_include_arguments_that_were_not_set():
        schema = GraphQLSchema(
            GraphQLObjectType(
                "Type",
                {
                    "field": GraphQLField(
                        GraphQLString,
                        args={
                            "a": GraphQLArgument(GraphQLBoolean),
                            "b": GraphQLArgument(GraphQLBoolean),
                            "c": GraphQLArgument(GraphQLBoolean),
                            "d": GraphQLArgument(GraphQLInt),
                            "e": GraphQLArgument(GraphQLInt),
                        },
                        resolve=lambda _source, _info, **args: inspect(args),
                    )
                },
            )
        )

        document = parse("{ field(a: true, c: false, e: 0) }")

        assert execute_sync(schema, document) == (
            {"field": "{'a': True, 'c': False, 'e': 0}"},
            None,
        )

    @mark.asyncio
    async def fails_when_is_type_of_check_is_not_met():
        class Special:
            value: str

            def __init__(self, value):
                self.value = value

        class NotSpecial:
            value: str

            def __init__(self, value):
                self.value = value

        def is_type_of_special(obj, _info):
            is_special = isinstance(obj, Special)
            if not _info.context["async"]:
                return is_special

            async def async_is_special():
                return is_special

            return async_is_special()

        SpecialType = GraphQLObjectType(
            "SpecialType",
            {"value": GraphQLField(GraphQLString)},
            is_type_of=is_type_of_special,
        )

        schema = GraphQLSchema(
            GraphQLObjectType(
                "Query", {"specials": GraphQLField(GraphQLList(SpecialType))}
            )
        )

        document = parse("{ specials { value } }")
        root_value = {"specials": [Special("foo"), NotSpecial("bar")]}

        result = execute_sync(schema, document, root_value, {"async": False})
        assert not isinstance(result, Awaitable)
        assert result == (
            {"specials": [{"value": "foo"}, None]},
            [
                {
                    "message": "Expected value of type 'SpecialType' but got:"
                    " <NotSpecial instance>.",
                    "locations": [(1, 3)],
                    "path": ["specials", 1],
                }
            ],
        )

        async_result = execute(schema, document, root_value, {"async": True})
        assert isinstance(async_result, Awaitable)
        awaited_result = await async_result
        assert awaited_result == result

    def fails_when_serialize_of_custom_scalar_does_not_return_a_value():
        custom_scalar = GraphQLScalarType(
            "CustomScalar", serialize=lambda _value: Undefined  # returns nothing
        )
        schema = GraphQLSchema(
            GraphQLObjectType(
                "Query",
                {
                    "customScalar": GraphQLField(
                        custom_scalar, resolve=lambda *_args: "CUSTOM_VALUE"
                    )
                },
            )
        )

        result = execute_sync(schema, parse("{ customScalar }"))
        assert result == (
            {"customScalar": None},
            [
                {
                    "message": "Expected `CustomScalar.serialize('CUSTOM_VALUE')`"
                    " to return non-nullable value, returned: Undefined",
                    "locations": [(1, 3)],
                    "path": ["customScalar"],
                }
            ],
        )

    def executes_ignoring_invalid_non_executable_definitions():
        schema = GraphQLSchema(
            GraphQLObjectType("Query", {"foo": GraphQLField(GraphQLString)})
        )

        document = parse(
            """
            { foo }

            type Query { bar: String }
            """
        )

        result = execute_sync(schema, document)
        assert result == ({"foo": None}, None)

    def uses_a_custom_field_resolver():
        schema = GraphQLSchema(
            GraphQLObjectType("Query", {"foo": GraphQLField(GraphQLString)})
        )
        document = parse("{ foo }")

        def field_resolver(_source, info):
            # For the purposes of test, just return the name of the field!
            return info.field_name

        result = execute_sync(schema, document, field_resolver=field_resolver)
        assert result == ({"foo": "foo"}, None)

    def uses_a_custom_type_resolver():
        document = parse("{ foo { bar } }")

        foo_interface = GraphQLInterfaceType(
            "FooInterface", {"bar": GraphQLField(GraphQLString)}
        )

        foo_object = GraphQLObjectType(
            "FooObject", {"bar": GraphQLField(GraphQLString)}, [foo_interface]
        )

        schema = GraphQLSchema(
            GraphQLObjectType("Query", {"foo": GraphQLField(foo_interface)}),
            types=[foo_object],
        )

        possible_types = None

        def type_resolver(_source, info, abstract_type):
            # Resolver should be able to figure out all possible types on its own
            nonlocal possible_types
            possible_types = info.schema.get_possible_types(abstract_type)
            return "FooObject"

        root_value = {"foo": {"bar": "bar"}}
        result = execute_sync(schema, document, root_value, type_resolver=type_resolver)

        assert result == ({"foo": {"bar": "bar"}}, None)
        assert possible_types == [foo_object]